Ejemplo n.º 1
0
def output( ):

	user = request.player
	try:
		id = getSingleField( 'id', request, getSingleFieldPOST('id', request )  )
		lad = db.GetLadder( id )
		if not db.AccessCheck( id, request.player.nick, Roles.GlobalAdmin ):
			template = env.get_template('error.html')
			return template.render( err_msg="you're not allowed to delete ladder #%s"%(str(id)) )
		ask = True
		if getSingleField( 'confirm', request  ) == 'yes':
			session = db.session()
			#figure out proper delete cascade instead
			SYNC_STRAT = 'fetch'
			session.query( Result ).filter( Result.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( Option ).filter( Option.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( Bans ).filter( Bans.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( GlickoRanks ).filter( GlickoRanks.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( SimpleRanks ).filter( SimpleRanks.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( TrueskillRanks ).filter( TrueskillRanks.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			matches = session.query( Match.id ).filter( Match.ladder_id == id )
			session.query( MatchSetting ).filter( MatchSetting.match_id.in_(matches) ).delete(synchronize_session=SYNC_STRAT)
			matches.delete()
			session.delete( lad )
			session.commit()
			session.close()
			ask = False
		template = env.get_template('deleteladder.html')
		return template.render( ladder=lad, ask=ask )

	except ElementNotFoundException, e:
		err = str(e)
Ejemplo n.º 2
0
def matches_per_player( playerid ):
	print 'not cached: matches_per_player( %s )'% playerid
	s = db.session()
	inc = timedelta(days=1)
	today = datetime.combine(date.today(), time.min ) #datetime( now.year, now.month, now.day )
	since = today - timedelta(days=7) - fail_offset
	now = since
	data = []
	i = 1
	while now < datetime.now() - fail_offset:
		data.append( s.query( Result.id ).filter( Result.player_id == playerid).filter( Result.date < now + inc ).filter( Result.date >= now ).count() )
		i += 1
		now += inc
	fn = 'images/plots/player_matches_%i.png'%int(playerid)
	path = os.path.join(config.get('ladder','base_dir'), fn)
	url = '%s/%s'%(config.get('ladder','base_url'), fn)
	mkdir_p(path)
	with mutex:
		f = plt.figure(1)
		plt.plot(range(len(data)),data)
		plt.ylabel('matches per day')
		plt.xlabel('days past')
		plt.savefig(path,transparent=True)
		plt.close(1)
	s.close()
	return url
Ejemplo n.º 3
0
	def get_rss_out(l_id):
		s = None
		try:
			base_url = config.get('ladder','base_url')
			s = db.session()			
			lad = db.GetLadder( ladder_id )
			rank_table = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( ladder_id ), db )
			#template = env.get_template('scoreboard.html')
			template = env.get_template('rss_scoreboard.html')
			desc = template.render( rank_table=rank_table, ladder=lad )
			url = '%sscoreboard?id=%s'%(base_url,ladder_id)
			#$postdate = date("Y-m-d H:i", $row['topic_time']);
			title = "%s -- updated scoreboard"%lad.name
			
			item = PyRSS2Gen.RSSItem( title = title, link=url, guid = PyRSS2Gen.Guid( url ), pubDate=datetime.datetime.now(), description = desc )
			rss = PyRSS2Gen.RSS2(
				title = "%s -- Scoreboard"%lad.name,
				link = "%sfeeds/scores/%s"%(base_url,l_id),
				description = "DESCRIPTION",
				lastBuildDate = datetime.datetime.now(),
				items = [item] )
			output = cStringIO.StringIO()
			rss.write_xml(output)
			return output.getvalue()
		
		except Exception, m:
			if 's' in locals() and s:
				s.close()
			return str(m)
Ejemplo n.º 4
0
	def get_rss_out(l_id):
		try:
			base_url = config.get('ladder', 'base_url')
			s = db.session()
			limit = 10
			matches = s.query( Match ).filter( Match.ladder_id == l_id )
			ladder_name = s.query( Ladder.name ).filter( Ladder.id == l_id ).one()
			items = get_items( matches )
			if len(items) == 0:
				return ""
			rss = PyRSS2Gen.RSS2(
				title = "%s -- Latest matches"%ladder_name,
				link = "%sfeeds/matches/%s"%(base_url,l_id),
				description = "Latest 10 matches played on a single given ladder",
				lastBuildDate = datetime.datetime.now(),
				items = items )
			output = cStringIO.StringIO()
			rss.write_xml(output)
			response.headers['Content-Type'] = 'text/xml'
			return output.getvalue()
		
		except Exception, m:
			if 's' in locals() and s:
				s.close()
			return str(m)
Ejemplo n.º 5
0
def output():
	try:
		s = db.session()
		limit = 10
		matches_header = 'Recent Matches'
		matches = s.query( Match ).order_by(Match.date.desc())[:limit]

		players_header = 'Active Players'
		player_ids = s.query( func.count( Result.player_id ), Result.player_id ).group_by( Result.player_id ).order_by( func.count(Result.player_id).desc() )[:limit]
		players = []
		for (count,pid) in player_ids:
			players.append( (s.query( Player ).filter( Player.id == pid ).one(), count ) )

		ladders_header = 'Active Ladders'
		ladder_ids = s.query( func.count( Match.ladder_id ), Match.ladder_id ).group_by( Match.ladder_id ).order_by( func.count(Match.ladder_id).desc() ).all()
		ladders = []
		for (count,lid) in ladder_ids:
			q = s.query( Ladder ).filter( Ladder.id == lid )
			if q.first():
				ladders.append( ( q.first(), count ) )


		template = env.get_template('index.html')
		ret = template.render( matches=matches, matches_header= matches_header, ladders_header=ladders_header, ladders=ladders, players_header=players_header, players=players  )
		s.close()
		return ret
		
	except Exception, m:
		if s:
			s.close()
		template = env.get_template('error.html')
		return template.render( err_msg=(str(m)) )
Ejemplo n.º 6
0
def output( ):
	try:
		s = db.session()
		stats = dict()
		stats['playercount'] = s.query(Player.id).count()
		matches = s.query(Match)
		stats['matchcount'] = matches.count()
		#stats['totalduration'] = s.query(func.sum(Match.duration).label('sum'))['sum']
		#kk = s.query(Match.duration).all()
		#print kk
		def _total_seconds(timedelta):
			if not hasattr(datetime.timedelta, 'total_seconds'):
				return timedelta.days * 86400.0 + timedelta.seconds + timedelta.microseconds * 1e-6
			return timedelta.total_seconds()
		stats['totalduration'] = sum([f[0] for f in s.query(Match.duration).all()], datetime.timedelta())
		stats['avgduration'] = str(datetime.timedelta(seconds=_total_seconds(stats['totalduration']) / float(stats['matchcount'])))
		stats['totalduration'] = str(stats['totalduration'] )
		stats['mostplayedmap'] = s.query(Match.mapname,func.count(Match.mapname).label('count')).group_by(Match.mapname).order_by('count DESC').first()
		stats['mostplayedgame'] = s.query(Match.modname,func.count(Match.modname).label('count')).group_by(Match.modname).order_by('count DESC').first()
		#stats['avgplayercount'] = func.avg(Match.
		print stats

		s.close()
		template = env.get_template('stats.html')
		return template.render(stats=stats)
		
	except ElementNotFoundException, e:
		err_msg="ladder with id %s not found"%(str(id))
Ejemplo n.º 7
0
def output( ):
	player_name = getSingleField( 'player', request )
	order = getSingleField( 'order', request , 'nick')
	ladder_id = getSingleField( 'ladder', request )
	try:
		s = db.session()
		if player_name:
			player = db.GetPlayer( player_name )
			ladders = db.GetLadderByPlayer( player.id )
			played = dict()
			positions = dict()
			for ladder in ladders:
				positions[ladder.id] = db.GetPlayerPosition( ladder.id, player.id )
				played[ladder.id] = s.query( Result.id ).filter( Result.ladder_id == ladder.id ).filter( Result.player_id == player.id ).count()

			results = s.query( Result ).filter( Result.player_id == player.id).order_by(Result.date.desc())[0:5]
			matches = [ r.match for r in results ]
			plot_url = plots.matches_per_player( player.id )

			template = env.get_template('viewplayer.html')
			s.close()
			return template.render(player=player,ladders=ladders, positions=positions,played=played,matches=matches,plot_url =plot_url  )
		else:
			asc = getSingleField( 'asc', request, 'False' )
			if not asc:
				asc = 'False'
			q = s.query( Player, func.count(Result.id).label('played')).outerjoin( (Result, Result.player_id == Player.id ) )\
				.filter( Player.id.in_(s.query( Result.player_id ).filter( Player.id == Result.player_id  ) ) ) \
				.filter( Result.player_id == Player.id ).group_by( Player.id )
			if ladder_id:
				q = q.filter( Player.id.in_( s.query( Result.player_id ).filter( Result.ladder_id == ladder_id ) ) )
			if order == 'nick':
				q = q.order_by( SortAsc( Player.nick, asc ) )
			elif order == 'id' :
				q = q.order_by( SortAsc( Player.id, asc ) )
			else:
				order = 'played'
				q = q.order_by( SortAsc( func.count(Result.id), asc ) )

			limit = int(getSingleField( 'limit', request, q.count() ))
			offset = int(getSingleField( 'offset', request, 0 ))
			players = q[offset:offset+limit-1]
			template = env.get_template('viewplayerlist.html')
			s.close()
			return template.render(players=players,offset=offset,limit=limit,order=order,asc=asc )

	except ElementNotFoundException, e:
		err_msg="player %s not found"%(str(player_name))
Ejemplo n.º 8
0
def output( ):
	limit = int(getSingleField( 'limit', request, 18 ))
	s = db.session()
	template = env.get_template('viewmaplist.html')
	if limit > -1:
		maps = s.query( Map ).all()#order_by(Map.name.desc()).limit(limit).all()
	else:
		maps = s.query( Map ).order_by(Map.name.desc()).all()
	ret = template.render( maps=maps, limit=limit )
	try:

		s.close()
		return ret
		
	except ElementNotFoundException, e:
		err_msg="map with id %s not found"%(str(id))
Ejemplo n.º 9
0
def output(  ):
	try:
		limit = 10
		template = env.get_template('fame.html')
		s = db.session()
		player_ids = s.query( Result.player_id ).group_by( Result.player_id )
		ladder_playerpos = dict()
		playerpos = []
		for pid in player_ids:
			pid = pid[0]
			ladders = s.query( Ladder ).filter( Ladder.id.in_( s.query( Result.ladder_id ).filter( Result.player_id == pid ).group_by( Result.ladder_id ) ) )
			score = 0
			l_names = []
			for l in ladders:
				player_per_ladder = s.query( Result.player_id ).filter( Result.ladder_id == l.id ).group_by( Result.player_id ).count()
				pos = db.GetPlayerPosition( l.id, pid )
				score += ( 0.5 - ( pos / float( player_per_ladder ) ) ) * 1000
				l_names.append( '%s (%d)'%(l.name,pos) )
			if ladders.count() > 0:
				playername = s.query( Player.nick ).filter( Player.id == pid ).first()[0]
				playerpos.append( (playername, int(score), ', '.join(l_names) ) )

		playerpos.sort( lambda x, y: cmp(y[1], x[1]) )
		header = ['Name', 'Score', 'Active on (position on ladder)' ]

		leaders = []
		losers = []
		for name, id in s.query( Ladder.name, Ladder.id ):
			try:
				r = db.GetRanks( id )
				if len(r) > 1:
					s.add( r[0] )
					s.add( r[-1] )
					leaders.append( (r[0].player.nick, name, r[-1].player.nick  ) )
			except ElementNotFoundException:
				continue #empty ladder
		losers.sort( lambda x, y: cmp(x[1], y[1]) )
		leaders.sort( lambda x, y: cmp(x[1], y[1]) )
		s.close()
		return template.render( playerpos_top=playerpos[0:limit],playerpos_bottom=playerpos[-limit:], header=header, leaders=leaders,losers=losers )

	except Exception, m:
		if s:
			s.close()
		template = env.get_template('error.html')
		return template.render( err_msg=(str(m)) )
Ejemplo n.º 10
0
def output( ):

	session = db.session()
	user = request.player
	try:
		id = getSingleField( 'id', request, getSingleFieldPOST('id', request )  )
		if not db.AccessCheck( id, request.player.nick, Roles.LadderAdmin ):
			template = env.get_template('error.html')
			session.close()
			return template.render( err_msg="you're not allowed to edit ladder #%s"%(str(id)) )
		pre = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( id ), db )
		db.RecalcRankings(id)
		post = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( id ), db )
		lad = db.GetLadder( id )
		template = env.get_template('recalc.html')
		session.close()
		return template.render( pre=pre, post=post, ladder=lad )

	except ElementNotFoundException, e:
		err = str(e)
Ejemplo n.º 11
0
def output():

    user = request.player
    try:
        session = db.session()
        id = getSingleField("id", request)
        mid = getSingleField("mid", request)
        if mid:
            if not db.AccessCheck(id, request.player.nick, Roles.LadderAdmin):
                template = env.get_template("error.html")
                return template.render(err_msg="you're not allowed to delete match #%s" % (str(mid)))
            lid = getSingleField("lid", request)
            db.DeleteMatch(lid, mid)
        if id:
            if db.AccessCheck(id, user.nick, Roles.LadderAdmin):
                ladder_ids = [id]
            else:
                ladder_ids = []
        else:
            if user.role < Roles.GlobalAdmin:
                ladder_ids = (
                    session.query(Option.ladder_id)
                    .filter(Option.key == Option.adminkey)
                    .filter(Option.value == user.nick)
                    .group_by(Option.ladder_id)
                )
            else:
                ladder_ids = session.query(Ladder.id)

        matches = (
            session.query(Match)
            .filter(Match.ladder_id.in_(ladder_ids))
            .order_by(Match.ladder_id)
            .order_by(Match.date.desc())
            .all()
        )
        template = env.get_template("adminmatch.html")
        return template.render(matches=matches, lid=id)

    except ElementNotFoundException, e:
        err = str(e)
Ejemplo n.º 12
0
def output( ):
	id = getSingleField( 'id', request, '-1' )
	try:
		s = db.session()
		if id == '-1':
			print 'LPLP %s'%id
			ladder_list = []
			ladder_triple_list = s.query(Ladder).order_by( Ladder.name )
			if ladder_triple_list.count() < 1:
				raise ElementNotFoundException('djwp')
			#ladder_triple_list = [db.GetLadder( 17 )]
			for  l in ladder_triple_list:
				ladder_id = l.id
				ladder_name = l.name
				ladder_description = l.description
				player_count = s.query( Result.id ).group_by( Result.player_id ).\
					filter(Result.ladder_id == ladder_id).count()
				match_query = s.query( Match.id,Match.date ).\
					filter(Match.ladder_id == ladder_id)
				match_count = match_query.count()
				last_match = match_query.order_by( Match.date.desc() ).first()

				item = dict()
				item['player_count'] = player_count
				item['match_count'] = match_count
				item['last_match'] = last_match
				item['name'] = ladder_name
				item['description'] = ladder_description
				item['id'] = ladder_id
				try:
					ranks = db.GetRanks( ladder_id, None, 3 )
					item['ranks'] = GlobalRankingAlgoSelector.GetWebRepresentation( ranks, db )
				except Exception, e:
					item['ranks'] = None
				ladder_list.append( item )
			template = env.get_template('viewladderlist.html')
			s.close()
			return template.render(ladders=ladder_list )
		else:
Ejemplo n.º 13
0
	def all_get_rss_out():
		try:
			base_url = config.get('ladder', 'base_url')
			s = db.session()
			limit = 10
			matches = s.query( Match )
			items = get_items( matches )
			if len(items) == 0:
				return ""
			rss = PyRSS2Gen.RSS2(
				title = "SpringLadder -- Latest matches",
				link = "%s/feeds/matches"%(base_url),
				description = "Latest 10 matches played on any ladder",
				lastBuildDate = datetime.datetime.now(),
				items = items )
			output = cStringIO.StringIO()
			rss.write_xml(output)
			return output.getvalue()
		
		except Exception, m:
			if 's' in locals() and s:
				s.close()
			return str(m)
Ejemplo n.º 14
0
def output( ):

	session = db.session()
	user = request.player
	try:
		if getSingleFieldPOST( 'addladder', request  ) == 'add':
			if user.role >= Roles.GlobalAdmin:
				name = getSingleFieldPOST( 'laddername', request )
				if name and len(name) > 0 and len(name) <= 100:
					ladderid = db.AddLadder( name )
					session.close()
					return bottle.redirect( '/admin/ladder?id=%d'%ladderid )
				else:
					template = env.get_template('error.html')
					session.close()
					return template.render( err_msg="you're not allowed to add a ladder" )
			else:
				template = env.get_template('error.html')
				session.close()
				return template.render( err_msg="you're not allowed to add a ladder" )
		if user.role < Roles.GlobalAdmin:
			ladder_ids = session.query( Option.ladder_id ).filter( Option.key == Option.adminkey ) \
				.filter( Option.value == user.nick ).group_by( Option.ladder_id )
		else:
			ladder_ids = session.query( Ladder.id )
		ladders = session.query( Ladder ).filter( Ladder.id.in_ ( ladder_ids ) ).all()
		template = env.get_template('adminindex.html')
		session.close()
		if len(ladders) < 1:
			#no admin whatsoever
			return bottle.redirect( '/' )
		return template.render( ladders=ladders, isglobal=user.role >= Roles.GlobalAdmin )

	except ElementNotFoundException, e:
		template = env.get_template('error.html')
		session.close()
		return template.render( err_msg=str(e) )
Ejemplo n.º 15
0
def output():

    id = getSingleField("id", request, getSingleFieldPOST("id", request))
    session = db.session()
    user = request.player
    note = ""
    extrainfo = None
    try:
        if not db.AccessCheck(id, request.player.nick, Roles.LadderAdmin):
            template = env.get_template("error.html")
            session.close()
            return template.render(err_msg="you're not allowed to edit ladder #%s" % (str(id)))
        lad = db.GetLadder(id)
        session.add(lad)
        options = lad.options
        to_delete = getFieldsByPrefixPOST("delete", request)
        if to_delete and len(to_delete) > 0:
            del_key = to_delete.keys()[0]
            if to_delete[del_key] == "delete":
                del_idx = int(del_key.split("-")[-1])
                del_opt = options[del_idx]
                session.delete(del_opt)
                session.commit()
                # redirect to same page here cause i had troubles with double session elements otherwise
                return bottle.redirect("/admin/ladder?id=%s" % id)
        if getSingleFieldPOST("addadmin", request) == "add":
            if not db.AccessCheck(id, request.player.nick, Roles.GlobalAdmin):
                template = env.get_template("error.html")
                session.close()
                return template.render(err_msg="you're not allowed to add an admin to ladder #%s" % (str(id)))
            admin_name = getSingleFieldPOST("adminname", request, "koko")
            db.AddLadderAdmin(id, admin_name)
            session.close()
            return bottle.redirect("/admin/ladder?id=%s" % id)
        if getSingleFieldPOST("new", request) == "add new option":
            opt = Option("", "")
            opt.ladder_id = id
            session.add(opt)
            session.commit()
            session.add(lad)
            options = lad.options
        form = forms.Ladder(request.POST, lad, options=options)
        if getSingleFieldPOST("submit", request) == "submit" and form.validate():
            extrainfo = handleAlgoChange(db, env, request, lad)
            form.populate_obj(lad)
            session.add(lad)
            session.commit()
            note = "Ladder updated"
            # else:#enable this for debug
            # if len(form.errors) > 0:
            # note= form.errors
        textfields = []
        for var in forms.Ladder.field_order:
            textfields.append(getattr(form, var))
        template = env.get_template("change_ladder.html")
        session.close()
        return template.render(
            form=form,
            ladder_id=id,
            note=note,
            textfields=textfields,
            isglobal=user.role >= Roles.GlobalAdmin,
            extrainfo=extrainfo,
        )

    except ElementNotFoundException, e:
        template = env.get_template("error.html")
        session.close()
        return template.render(err_msg=str(e))