Source

namethatanime / hw.py

  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
# -*- coding: utf-8 -*-
import sys, os
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
import traceback
from itertools import cycle
from game.game import Game, GameException, GameProcedureError, message
from game.database import db
from time import gmtime, strftime
import hashlib
import bcrypt
import re
import json
import amonpy
from game.exce import ntae
import pylibmc
from array import array

mc = pylibmc.Client(['127.0.0.1:11211'], binary=True,behaviors={"tcp_nodelay": True,"ketama": True})

loader = tornado.template.Loader(os.path.join(os.path.join(os.path.realpath(__file__) + '/../'), 'templates'))

games = []
users = {}

class UserData(object):
    def __init__(self, id, name):
        self.id = int(id)
        self.name = name

# Additional method for every request, to get current user name and id
class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        if self.get_secure_cookie("user"):
            if not users.has_key(self.get_secure_cookie("user")):
                users[self.get_secure_cookie("user")] = {}
            return UserData(self.get_secure_cookie("userid"), self.get_secure_cookie("user"))
        else:
            return None

# Creates new game object, it's id will be address of game
class NewGameHandler(BaseHandler):
    def get(self):
        try:
            length = int(self.get_argument('len', 1))
            diff = int(self.get_argument('diff', 1))
            ranked = False
            if self.get_current_user():
                ranked = True
                username = self.get_current_user().name
                if users[username].has_key('game'):
                    # User still has previous game, remove it if it ended 
                    for g in games:
                        if users[username]['game'] == g and g.ended:
                            print "to ta gra, usuwamy"
                            games.remove(g)
                            del users[username]['game']
                            break
            game = Game(length, diff, ranked)
            game.url = '/' + str(id(game))
            games.append(game)
            #amonpy.log('Created new game %s' % str(id(game)), level='info')
            self.redirect(game.url)
        except Exception, e:
            ntae.process_exception(e, {'handler':'NewGameHandler'})

# Index page of website
class LobbyHandler(BaseHandler):    
    def get(self):
        try:
            if self.request.host.startswith('donate.'):
                self.write(loader.load('donate.html').generate(user=self.get_current_user(), charge=None))
            else:
                self.write(loader.load('index.html').generate(user=self.get_current_user()))
        except Exception, e:
            ntae.process_exception(e, {'handler':'LobbyHandler'})

# Passwords protected with bcrypt
class LoginHandler(BaseHandler):
    def get(self):
        try:       
            self.write(loader.load('login.html').generate(user=self.get_current_user(), emptypass=False, emptyuser=False, err=False))
        except Exception, e:
            ntae.process_exception(e, {'handler':'LoginHandler'})
        
    def post(self):
        try:
            username = self.get_argument("login", default='')
            emptyuser = ( username == '')     
            passwd = self.get_argument("passwd", default='')
            emptypass = ( passwd == '') 
            if (emptyuser or emptypass):
                self.write(loader.load('login.html').generate(emptyuser=emptyuser, emptypass=emptypass, err=False))
                return None    
            query = db.get("SELECT id, password FROM namethatanime_user where username = %s", (username,))
            ##print query
            if query:
                hashed = query.password
                if bcrypt.hashpw(passwd, hashed) == hashed:
                    ## Password match
                    user_id = query.id
                    if user_id:
                        print "username= " + username
                        print "user id= " + str(user_id)
                        self.set_secure_cookie("user", username)
                        self.set_secure_cookie("userid", str(user_id))
                        if not users.has_key(username):
                            users[username] = {}
                        self.redirect("/")
                        return
            ## Wrong password
            self.write(loader.load('login.html').generate(emptypass=False, emptyuser=False, err=True))
        except Exception, e:
            ntae.process_exception(e, {'handler':'LoginHandler'})

class RegisterHandler(BaseHandler):
    def get(self):
        try:
            self.write(loader.load('registernew.html').generate(user=self.get_current_user(), emptypass=False, emptypass2=False, emptyuser=False, emptyemail=False, dontmatch=False, username='', email='', useduser=False, usedemail=False, specchar=False))
        except Exception, e:
            ntae.process_exception(e, {'handler':'RegisterHandler'})
        
    def post(self):
        try:
            specchar = False
            emptypass = False
            emptypass2= False
            dontmatch = False
            emptyuser = False
            useduser = False
            emptyemail= False
            usedemail = False
            username = self.get_argument("login", default='')
            email = self.get_argument("email", default='')    
            passwd = self.get_argument("passwd", default='') 
            if passwd == '':
                emptypass = True
            if self.get_argument("passwd2", default='') == '':
                emptypass2 = True
            if username == '':
                emptyuser = True
            if email == '':
                emptyemail = True
            if self.get_argument("passwd", default='') != self.get_argument("passwd2", default=''):
                dontmatch = True
            p = re.compile('(\w+)')
            if p.match(username).group() != username:
                specchar = True
            if (emptypass or emptypass2 or emptyuser or emptyemail or dontmatch or specchar):
                self.write(loader.load('registernew.html').generate(user=self.get_current_user(),specchar=specchar,emptypass=emptypass, emptypass2=emptypass2, emptyuser=emptyuser, emptyemail=emptyemail, dontmatch=dontmatch, username=username,email=email, useduser=useduser, usedemail=usedemail))
                return None
            hashed = bcrypt.hashpw(passwd, bcrypt.gensalt())
            query = "SELECT ID FROM namethatanime_user where username = %s"
            user_id = db.get(query, (username,))
            if user_id:
                useduser = True
            emailquery = "SELECT ID FROM namethatanime_user where username = %s"
            email_id = db.get(emailquery, (username,))
            if email_id or user_id:
                usedemail = True
            if useduser or usedemail:
                self.write(loader.load('registernew.html').generate(user=self.get_current_user(),specchar=specchar,emptypass=emptypass, emptypass2=emptypass2, emptyuser=emptyuser, emptyemail=emptyemail, dontmatch=dontmatch, username=username,email=email, useduser=useduser, usedemail=usedemail))
                return None
            regquery = "INSERT INTO namethatanime_user (username, password, email) VALUES(%s,%s,%s) RETURNING id"
            user_id = db.get(regquery, (username, hashed, email,)).id
            self.set_secure_cookie("user", username)            
            self.set_secure_cookie("userid", str(user_id))
            if not users.has_key(username):
                users[username] = {}    
            #amonpy.log('Registered new user: %s' % username, level='info')        
            self.redirect("/")
        except Exception, e:
            ntae.process_exception(e, {'handler':'RegisterHandler'})

class LogoutHandler(BaseHandler):
    def get(self):
        try:
            self.set_secure_cookie("user", "")
            self.redirect('/')
        except Exception, e:
            ntae.process_exception(e, {'handler':'LogoutHandler'})
        
### GRA
class GameHandler(BaseHandler):
    def get(self, game_id):
        try:
            self.write(loader.load('game.html').generate(game_id=game_id))
        except Exception, e:
            ntae.process_exception(e, {'handler':'GameHandler'})

class JoinGameHandler(BaseHandler):
    def get(self, game_id):
        try:
            user=self.get_current_user()
            game = None
            for g in games:
                if str(id(g)) == game_id:
                    game = g
            if game == None:
                self.write(loader.load('game.html').generate(game_id='0'))
                return None   
            player = None  
            if game.ranked:
                if users[self.get_current_user().name].has_key('game'):   
                    player = users[self.get_current_user().name]['player']
                    player.left = False
                else:
                    # Create new player
                    player = game.player_factory(self.get_current_user().name, game) 
                    player.id = user.id
                    player.banned = db.get("SELECT banned_anime FROM namethatanime_user where id = %s", (player.id,)).banned_anime
                    game.add_player(player, player)
                    users[self.get_current_user().name]['player'] = player
                    users[self.get_current_user().name]['game'] = game
            else:
                player = game.player_factory(self.xsrf_token, game) 
                player.id = -1
                game.add_player(player, player)
                users[self.xsrf_token] = {}
                users[self.xsrf_token]['player'] = player
            self.write(loader.load('gamenew.html').generate(player=player, game_id=game_id, user=user))
        except Exception, e:
            ntae.process_exception(e, {'handler':'JoinGameHandler'})

class QuitGameHandler(BaseHandler):
    def get(self, game_id):
        try:
            users[self.get_current_user().name]['game'].player_quit(users[self.get_current_user().name]['player'])
            users[self.get_current_user().name].pop('player')
            users[self.get_current_user().name].pop('game')
            game = None
            for g in games:
                if str(id(g)) == game_id:
                    game = g
            if game != None:
                if not game.players:
                    games.remove(game)
                    del game
            self.redirect("/")
        except Exception, e:
            ntae.process_exception(e, {'handler':'QuitGameHandler'})

class QuestionGameHandler(BaseHandler):
    def get(self, game_id):
        try:
            player = None    
            if self.get_current_user():
                player = users[self.get_current_user().name]['player']
            else:
                player = users[self.xsrf_token]['player']
            self.write(loader.load('questionnew.html').generate(player=player,game_id=game_id))
        except Exception, e:
            ntae.process_exception(e, {'handler':'QuestionGameHandler'})
        
class PointsGameHandler(BaseHandler):
    def get(self, game_id):
        try:
            player = None    
            if self.get_current_user():
                player = users[self.get_current_user().name]['player']
            else:
                player = users[self.xsrf_token]['player']
            self.write(loader.load('pointsnew.html').generate(player=player,game_id=game_id))
        except Exception, e:
            ntae.process_exception(e, {'handler':'PointsGameHandler'})

class LastSongGameHandler(BaseHandler):
    def get(self, game_id):
        try:  
            player = None    
            if self.get_current_user():
                player = users[self.get_current_user().name]['player']
            else:
                player = users[self.xsrf_token]['player']  
            self.write(loader.load('lastsong.html').generate(player=player,game_id=game_id))
        except Exception, e:
            ntae.process_exception(e, {'handler':'LastSongGameHandler'})

class DebugGameHandler(BaseHandler):
    def get(self, game_id):        
        self.write(loader.load('debug.html').generate(player=users[self.get_current_user().name]['player'],game_id=game_id))
                       
# ZWYKLE

class HelpHandler(BaseHandler):
    def get(self):        
        self.write(loader.load('help.html').generate(user=self.get_current_user()))
        
class DonateHandler(BaseHandler):
    def get(self):        
        self.write(loader.load('donate.html').generate(user=self.get_current_user(), charge=None))
        
class ContactHandler(BaseHandler):
    def get(self):        
        self.write(loader.load('contact.html').generate(user=self.get_current_user()))
        
class AboutHandler(BaseHandler):
    def get(self):        
        self.write(loader.load('about.html').generate(user=self.get_current_user()))

# USER PROFILE
        
class AddBannedHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self, user_id):
        try:
            user = self.get_current_user()
            anime_id = self.get_argument("anime_id", default='-1')
            banned = db.get("SELECT banned_anime FROM namethatanime_user where id = '%s'", (user.id,)).banned_anime
            if (banned == None):
                # No banned yet
                banned = (anime_id,) 
            else:
                # Juz sa
                banned = json.loads(banned)
                if (len(banned) < 10):
                    banned.append(anime_id)
                else:
                    self.write('toomany')
                    return            
            db.execute("UPDATE namethatanime_user SET banned_anime= %s WHERE id = '%s'", (json.dumps(banned), user.id,) )
            self.write("ok")
        except Exception, e:
            self.write('database error')
            ntae.process_exception(e, {'handler':'AddBannedHandler'})

class RemoveBannedHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self, user_id):
        try:
            user = self.get_current_user()
            anime_id = self.get_argument("anime_id", default='-1')
            banned = db.get("SELECT banned_anime FROM namethatanime_user where id = '%s'", (user.id,)).banned_anime            
            banned = json.loads(banned)
            banned.remove(anime_id)       
            db.execute("UPDATE namethatanime_user SET banned_anime= %s WHERE id = '%s'", (json.dumps(banned), user.id,) )
            self.write("ok")
        except Exception, e:
            self.write('database error')
            ntae.process_exception(e, {'handler':'RemoveBannedHandler'})

        
class UserHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, user_id):
        try:    
            tab = int(self.get_argument("tab", default='1')) 
            self.write(loader.load('user.html').generate(user=self.get_current_user(), tab=tab, game_id=None))
        except Exception, e:
            ntae.process_exception(e, {'handler':'UserHandler'})
        
class UserSettingsHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, user_id):
        try:
            user=self.get_current_user()
            banned = db.get("SELECT banned_anime FROM namethatanime_user where id = '%s'", (user.id,)).banned_anime
            if banned:
                banned = str(tornado.escape.json_decode(banned)).replace('u\'', '\'')
            self.write(loader.load('user_settings.html').generate(user=user, banned=banned))
        except Exception, e:
            ntae.process_exception(e, {'handler':'UserSettingsHandler'})
            
class UserStatsHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, user_id):
        try:
            user=self.get_current_user()
            stats = {}
            stats['games'] = db.execute_rowcount('SELECT * FROM namethatanime_usergames WHERE user_id = %s;', (user.id,))   
            stats['correct'] = db.execute_rowcount('SELECT * FROM namethatanime_questionlog WHERE user_id = %s AND correct;', (user.id,))  
            stats['wrong'] = db.execute_rowcount('SELECT * FROM namethatanime_questionlog WHERE user_id = %s AND NOT correct AND CAST(answer as integer) > -2;', (user.id,))  
            stats['unanswered'] = db.execute_rowcount("SELECT * FROM namethatanime_questionlog WHERE user_id = %s AND answer = '-2';", (user.id,))
            total = stats['correct'] + stats['wrong'] + stats['unanswered']   
            if total > 0:
                stats['avgpts'] = '%.2f' % db.get("SELECT avg(CAST(points as integer)) FROM namethatanime_questionlog WHERE user_id = %s;", (user.id,)).avg
                stats['avgtime'] = '%.2f' % db.get("SELECT avg(CAST(anstime as integer)) FROM namethatanime_questionlog WHERE user_id = %s;", (user.id,)).avg            
                stats['corpercent'] = "{0:.0%}".format(float(stats['correct']) / float(total))
            else:
                stats['avgpts'] = 0
                stats['avgtime'] = 0
                stats['corpercent'] = 0
            self.write(loader.load('user_stats.html').generate(user=user, stats=stats))
        except Exception, e:
            ntae.process_exception(e, {'handler':'UserStatsHandler'})

class UserGamesHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, user_id):  
        try:    
            user=self.get_current_user()
            page = int(self.get_argument("page", default='1'))
            limit = 20
            que = db.query('''SELECT 
              to_char(gl.start_date, 'YYYY-MM-DD HH24:MI') as start,  
              to_char((gl.end_date - gl.start_date), 'HH24:MI:SS')  as length, 
              gl.rounds, 
              gl.questions, 
              gl.diff, 
              ug.result, 
              gl.id, 
              ug.game_id, 
              ug.user_id
            FROM 
              public.namethatanime_usergames ug, 
              public.namethatanime_gamelog gl
            WHERE 
              gl.id = ug.game_id AND
              ug.user_id = '%s'
            ORDER BY start DESC
            LIMIT %s OFFSET '%s';''', (user.id, limit, limit*(page-1),))
            pages = db.execute_rowcount('SELECT id FROM public.namethatanime_usergames ug WHERE ug.user_id = %s;', (user.id,))/limit        
            pages = pages + 2 # Start from 1
            self.write(loader.load('user_games.html').generate(user=user, games=que, page=page, pages=pages))
        except Exception, e:
            ntae.process_exception(e, {'handler':'UserGamesHandler'})

class UserViewGameHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, user_id, game_id):  
        try: 
            user=self.get_current_user()
            tab = 2
            game = db.get('''SELECT  
            to_char(gl.start_date, 'YYYY-MM-DD HH24:MI') as start,  
            to_char((gl.end_date - gl.start_date), 'HH24:MI:SS')  as length, 
            gl.rounds, 
            gl.questions, 
            gl.diff
            FROM namethatanime_gamelog gl WHERE gl.id = %s;''', (game_id,))
            questions = db.query('SELECT ql.song_id, votes, choices, answer, anstime, points, ql.anime_id, title, uv.vote FROM namethatanime_questionlog ql JOIN namethatanime_song so ON so.id = ql.song_id LEFT JOIN namethatanime_uservotes uv ON uv.song_id = ql.song_id AND uv.user_id = %s WHERE ql.game_id = %s ORDER BY ql.id;', (user.id, game_id,))
            artists = []
            for q in questions:
                art = db.query('SELECT name FROM namethatanime_artist INNER JOIN namethatanime_song_artist ON namethatanime_artist.id = namethatanime_song_artist.artist_id WHERE song_id = %s;', (q.song_id,))
                artists.append(art)   
            stats = {}             
            stats['correct'] = db.execute_rowcount('SELECT * FROM namethatanime_questionlog WHERE user_id = %s AND correct AND game_id = %s;', (user.id, game_id,))  
            stats['wrong'] = db.execute_rowcount('SELECT * FROM namethatanime_questionlog WHERE user_id = %s AND game_id = %s AND NOT correct AND CAST(answer as integer) > -2;', (user.id, game_id,))  
            stats['unanswered'] = db.execute_rowcount("SELECT * FROM namethatanime_questionlog WHERE user_id = %s AND game_id = %s AND answer = '-2';", (user.id, game_id,))
            stats['total'] = stats['correct'] + stats['wrong'] + stats['unanswered']   
            if stats['total'] > 0:
                stats['sumpts'] = db.get("SELECT sum(CAST(points as integer)) FROM namethatanime_questionlog WHERE user_id = %s AND game_id = %s;", (user.id, game_id,)).sum
                stats['avgtime'] = '%.2f' % db.get("SELECT avg(CAST(anstime as integer)) FROM namethatanime_questionlog WHERE user_id = %s AND game_id = %s;", (user.id, game_id,)).avg            
                stats['corpercent'] = "{0:.0%}".format(float(stats['correct']) / float(stats['total']))
            else:
                stats['sumpts'] = 0
                stats['avgtime'] = 0
                stats['corpercent'] = 0
            self.write(loader.load('user.html').generate(user=user, tab=tab, game_id=game_id, g=game, questions = questions, artists=artists, stats=stats))
        except Exception, e:
            ntae.process_exception(e, {'handler':'UserViewGameHandler'})
            
class UserSugSongsHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, user_id):  
        try: 
            user = self.get_current_user()
            tab = 3
            sugsongs = db.query("SELECT title, anime, artist, comm, mycomm, status FROM namethatanime_usersugestedsong WHERE user_id = %s ", (user.id,))
            self.write(loader.load('user_sugsongs.html').generate(user=user, tab=tab, sugsongs=sugsongs))
        except Exception, e:
            ntae.process_exception(e, {'handler':'UserSugSongsHandler'})

# Songs
class SuggestSongHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        try:
            user = self.get_current_user()
            title = self.get_argument("title", default='')
            artist = self.get_argument("artist", default='')
            anime = self.get_argument("anime", default='')
            comm = self.get_argument("comm", default='')
            db.execute("INSERT INTO namethatanime_usersugestedsong (user_id, title, artist, anime, comm, mycomm, status) VALUES (%s, %s, %s, %s, %s, '', 'N');", (user.id, title, artist, anime, comm,))            
            self.write("ok")
        except Exception, e:
            self.write('database error')
            ntae.process_exception(e, {'handler':'SuggestSongHandler'})
            
class SongVoteHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        try:
            user = self.get_current_user()
            song_id = int(self.get_argument("song_id", default='-1'))
            val = int(self.get_argument("val", default='-2'))
            if song_id != -1:
                vote = db.get("SELECT * FROM namethatanime_uservotes WHERE user_id = '%s' AND song_id = '%s'", (user.id,song_id,))       
                if vote:
                    db.execute("UPDATE namethatanime_uservotes SET vote= '%s' WHERE user_id = '%s' AND song_id = '%s'", (val, user.id, song_id,))
                else:
                    db.execute("INSERT INTO namethatanime_uservotes (user_id, song_id, vote) VALUES ('%s', '%s', '%s');", (user.id, song_id, val,))               
                self.write("ok")
        except Exception, e:
            self.write('database error')
            ntae.process_exception(e, {'handler':'SongVoteHandler'})
            
# Baza 
class ViewDataHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):  
        try:         
            songs = mc.get("songs")
            if not songs:
                songs = db.execute_rowcount('SELECT * FROM namethatanime_song;')
                mc.set("songs", songs, 8*3600)
            artists = mc.get("artists")
            if not artists:                
                artists = db.execute_rowcount('SELECT * FROM namethatanime_artist;')   
                mc.set("artists", artists), 8*3600
            anime = mc.get("anime")
            if not anime:  
                anime = db.execute_rowcount('SELECT * FROM namethatanime_anime;')   
                mc.set("anime", anime, 8*3600)
            self.write(loader.load('viewdata.html').generate(user=self.get_current_user(), songs=songs, artists=artists, anime=anime))
        except Exception, e:
            ntae.process_exception(e, {'handler':'ViewDataHandler'})
            
class ViewSongsHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):  
        try:                   
            songs = mc.get("allsongs")
            if not songs:
                songs = db.queryDict("SELECT * FROM namethatanime_song ORDER BY lower(title)")
                mc.set("allsongs", songs, 3600)
            self.write(loader.load('viewsongs.html').generate(user=self.get_current_user(), songs=songs))
        except Exception, e:
            ntae.process_exception(e, {'handler':'ViewSongsHandler'})
            
class ViewArtistsHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):  
        try:
            artists = mc.get("allartists")  
            if not artists:
                artists = db.queryDict("SELECT *, (SELECT COUNT(*) FROM namethatanime_song_artist sa WHERE sa.artist_id = a.id) as songs FROM namethatanime_artist a ORDER BY lower(name)")
                mc.set("allartists", artists, 3600)   
            self.write(loader.load('viewartists.html').generate(user=self.get_current_user(), artists=artists))
        except Exception, e:
            ntae.process_exception(e, {'handler':'ViewArtistsHandler'})
            
class ViewAnimeHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):  
        try:     
            anime = mc.get("allanime")  
            if not anime:
                anime = db.queryDict("SELECT *, (SELECT COUNT(*) FROM namethatanime_song sa WHERE sa.anime_id = a.id) as songs FROM namethatanime_anime a ORDER BY lower(title)")
                mc.set("allanime", anime, 3600)     
            self.write(loader.load('viewanime.html').generate(user=self.get_current_user(), anime=anime))
        except Exception, e:
            ntae.process_exception(e, {'handler':'ViewAnimeHandler'})            
       
# SOCKETY
class PlayerWebSocket(tornado.websocket.WebSocketHandler):
    def open(self, user):        
        self.player = users[user]['player']
        self.player.socket = self
        #print "ws open"
    
    def on_message(self, message):
        #print "jest msg " + message
        if (message.startswith("ch=")):
            self.player.game.broadcast(strftime("|%H:%M:%S| ", gmtime()) + "[" + self.player.name + "]: " + message[3:])
        elif (message.startswith("!rdy")):
            #print "recieved songready from pl " + self.player.name
            self.player.songready = True
        elif (message.startswith("!plrdy")):
            #print "recieved ready from pl " + self.player.name
            self.player.ready = True
            self.player.game.broadcast("!rlquestion") 
        elif (message.startswith("!tup")):
            #print "koniec!"
            self.player.game.broadcast("!st")
        else:
            #print message
            try:
                params = message.split(' ')
                self.player.callbacks[params[0]](message=' '.join(params[1:]))
            except Exception, e:
                self.write_message('Uncaught:' + str(e))
                ntae.process_exception(e, {'test':'1'})
                traceback.print_exc()
        # Keep receiving messages
        ##self.receive_message(self.on_message)

    def on_close(self):
        print "WebSocket closed"

class EchoWebSocket(tornado.websocket.WebSocketHandler):
    def open(self, user):
        print "WebSocket opened"

    def on_message(self, message):
        self.write_message(u"ch=You said: " + message)

    def on_close(self):
        print "WebSocket closed"

settings = {'static_path': os.path.join(os.path.realpath(__file__ + '/../'), 'static'),
            'cookie_secret': 'QR%9F4\'?J$@(Z0V($5?@([_.8B&%UOD1H5Y.JMJ',
            'login_url'    : '/login',
            'gzip' : True,
            'debug' : False}

application = tornado.web.Application(
    [(r'/',      LobbyHandler),
     (r'/login',   LoginHandler),
     (r'/register',   RegisterHandler),
     (r'/help',   HelpHandler),
     (r'/donate',   DonateHandler),
     (r'/about',   AboutHandler),
     (r'/contact',   ContactHandler),
     (r'/new', NewGameHandler),
     (r'/logout',   LogoutHandler),
     (r'/data/songs',   ViewSongsHandler),
     (r'/data/artists',   ViewArtistsHandler),
     (r'/data/anime',   ViewAnimeHandler),
     (r'/data',   ViewDataHandler),
     (r'/(\d+)$', JoinGameHandler),
     (r'/(\d+)/end', QuitGameHandler),
     (r'/(\d+)/question', QuestionGameHandler),
     (r'/(\d+)/points', PointsGameHandler),
     (r'/(\d+)/lastsong', LastSongGameHandler),
     (r'/(\d+)/debug', DebugGameHandler),
     (r'/u(\d+)/games/g(\d+)$', UserViewGameHandler),
     (r'/u(\d+)/games', UserGamesHandler),
     (r'/u(\d+)/settings/addban', AddBannedHandler),
     (r'/u(\d+)/settings/remban', RemoveBannedHandler),
     (r'/u(\d+)/settings', UserSettingsHandler),
     (r'/u(\d+)/stats', UserStatsHandler),
     (r'/u(\d+)/sugested', UserSugSongsHandler),
     (r'/songvote', SongVoteHandler),
     (r'/suggestsong', SuggestSongHandler),
     (r'/u(\d+)', UserHandler),
     (r'/ws(\w+)/get', PlayerWebSocket)],
    **settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()