Esempio n. 1
0
    def __call__(self):
        dbsession = DBSession()
        location = "A"
        location = "%s%s" % (location, self.request.matchdict.get("galaxy"))
        location = "%s:%s" % (location, self.request.matchdict.get("region"))
        location = "%s:%s" % (location, self.request.matchdict.get("system"))
        location = "%s:%s" % (location, self.request.matchdict.get("astro"))

        astro = dbsession.query(Location).filter(Location.location==location).one()
        base = astro.base
        fleets = dbsession.query(Fleet).filter(Fleet.location==location)
        fleets = fleets.order_by("arrival-(unix_timestamp(now())-unix_timestamp(fleet.timestamp)) > 0 ASC, arrival ASC, size DESC")
        fleets_count = fleets.count()
        if fleets_count == 0:
            fleets = []


        blobdetails = createBlobDetails(location, fleets)
        blobdetails = blobdetails.values()
        def blobsize_compare(x, y):
            xsum = x['sum']
            ysum = y['sum']
            return int(ysum - xsum)
        blobdetails = sorted(blobdetails, cmp=blobsize_compare)

        returnvalue = { 'location':location,
                        'astrolocation':astro,
                        'base':base,
                        'fleets':fleets,
                        'fleets_count':fleets_count,
                        'datetime':datetime,
                        'blobdetails':blobdetails
        }
        returnvalue.update(self.request.matchdict)
        return returnvalue
Esempio n. 2
0
    def __call__(self):
        dbsession = DBSession()
        bases = dbsession.query(Base.loc_gal, func.count('*').\
         label('base_count'), select(["FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(base.timestamp)))"]).label("average_age")).\
         group_by(Base.loc_gal)

        astros = dbsession.query(Location.loc_gal,func.count(Location.location).label('astro_count'))
        astros = astros.group_by(Location.loc_gal)

        galaxies = {}

        for row in range(0,80):
            galaxies["A%s"%twodigitNumbers(row)] = {}

        for astro_location,astro_count in astros:
            row = astro_location
            galaxy_info = galaxies[row]
            galaxy_info['astro_count'] = astro_count
            galaxy_info['base_count'] = 0
            galaxy_info['base_age'] = -1

        for base_location, base_count, base_age in bases:
            row = base_location
            if row:
                galaxy_info = galaxies[row]
                galaxy_info['base_count'] = base_count
                galaxy_info['base_age'] = getAgeColorTimedelta(datetime.now() - base_age)
                galaxies[row] = galaxy_info


        legenda = getAgeLegenda()

        return {'galaxies':galaxies,
                'legenda':legenda,
                'datetime':datetime}
Esempio n. 3
0
    def membersubmit(self):
        params = self.request.params
        import transaction
        session = DBSession()
        ourvalues = {}
        try:
            userid = params.get('userid')
            groupid = params.get('groupid')
            player = session.query(Player).filter(Player.id==userid).one()
            group = session.query(Group).filter(Group.id==groupid).one()
            if 'removefromgroup' in params:
                membership = session.query(GroupMembership) \
                    .filter(
                        and_(GroupMembership.groupid==groupid,
                             GroupMembership.userid==userid)) \
                    .first()
                session.delete(membership)
                ourvalues['message'] = 'Succesfully removed %s from %s ' % (player.name, group.name)
                transaction.commit()
            if 'addtogroup' in params:

                membership = GroupMembership(userid, groupid)
                session.add(membership)
                ourvalues['message'] = 'Succesfully added %s to %s ' % (player.name, group.name)
                transaction.commit()

        except:
            pass
        returnvalue =  self.grouplist()
        returnvalue.update(ourvalues)
        return returnvalue
Esempio n. 4
0
    def grouplist(self):
        session = DBSession()


        returnvalue = {}
        returnvalue['current_groups'] = session.query(Group)
        returnvalue['group'] = None
        returnvalue['users'] = None
        groupid = self.request.matchdict.get('groupid',None)
        if groupid:

            ##TODO: members kloppen niet.
            group = session.query(Group).filter(Group.id==groupid).one()
            returnvalue['group'] =  group

            users = session.query(User).filter(~User.groups.any(Group.id==groupid))
            users = users.join(User.guild)
            users = users.join(User.player)
            users = users.order_by(GuildInfo.id, Player.name)
            returnvalue['optional_users'] =  users

        guilds = session.query(GuildInfo).filter(GuildInfo.alive==1)
        returnvalue['optional_guilds'] =  guilds

        returnvalue['message'] = None

        return returnvalue
Esempio n. 5
0
    def __call__(self):
        dbsession = DBSession()
        bases=None
        fleetstrings = {}
        params = self.request.params


        if "form.submitted" in self.request.params:
            def url_generator(**kw):
                new_url = update_params(self.request.url, page=kw['page'])
                return new_url

            params = self.request.params

            bases = dbsession.query(Base)

            bases = performBaseFilter(bases, params)

            ##Sorting

            if 'sort_field' in self.request.params and self.request.params.get('sort_field') != '':
                bases = performBaseSort(bases, self.request.params)
                
#

                
            ##Limits and such
            per_page = int(self.request.params.get('per_page') or 100)
            bases = paginate.Page(bases, page=int(self.request.params.get('page', 1)), items_per_page=per_page, url=url_generator, item_count=bases.count())

            if 'show_ofs' in self.request.params:
                locationdetail = {}
                fleetlocations = []
                for base in bases:
                    locationdetail[base.location] = { "owner_id":base.ownerid, "owner_guild_id":(base.owner and base.owner.guild) and base.owner.guild.id or -1}
                    fleetlocations.append(base.location)

                fleets = dbsession.query(Fleet).filter(Fleet.location.in_(fleetlocations)).all()

                fleetstrings = {}

                for fleet in fleets:
                    locdetail = locationdetail.get(fleet.location)
                    fleetdetail = fleetstrings.get(fleet.location, {})
                    if fleet.ownerid == locdetail.get("owner_id"):
                        fleetdetail['owner'] = fleetdetail.get('owner',0) + fleet.size
                    elif (fleet.owner and fleet.owner.guild) and fleet.owner.guild.id == locdetail.get("owner_guild_id"):
                        fleetdetail['guild'] = fleetdetail.get('guild',0) + fleet.size
                    else:
                        fleetdetail['other'] = fleetdetail.get('other',0) + fleet.size
                    fleetstrings[fleet.location] = fleetdetail

        return {"filters": self.filters,
                "fieldfilters" : self.fieldfilters,
                "bases":bases,
                "params":params,
                "fleetstrings":fleetstrings,
                "datetime":datetime}
    def userlist(self):
        dbsession = DBSession()


        returnvalue = {}
        returnvalue['to_activate'] = dbsession.query(User).filter(and_(User.activated==0,User.banned==0))
        returnvalue['activate'] = dbsession.query(User).filter(and_(User.activated==1,User.banned==0))
        returnvalue['banned'] = dbsession.query(User).filter(User.banned==1)

        returnvalue['message'] = None
        
        return returnvalue
Esempio n. 7
0
    def __call__(self):
        dbsession = DBSession()
        returnvalue = {}
        returnvalue.update(self.request.matchdict)
        fleetid = returnvalue.get('fleetid')

        fleet = dbsession.query(Fleet).filter(Fleet.id==fleetid).one()

        returnvalue['fleet'] = fleet

        return returnvalue
    def submit(self):
        params = self.request.params
        import transaction
        session = DBSession()
        ourvalues = {}
        
        playerid = params.get('playerid')
        player = session.query(User).filter(User.playerid==playerid).one()
        if 'ban' in params:
            player.banned = 1
            player.banned_on = datetime.now()
            transaction.commit()
            ourvalues['message'] = 'Succesfully banned player: %s ' % playerid
        if 'unban' in params:
            player.banned = 0
            player.banned_on = ''
            transaction.commit()
            ourvalues['message'] = 'Succesfully unbanned player: %s ' % playerid

        if 'activate' in params:
            player.activated = 1
            player.activated_on = datetime.now()
            transaction.commit()
            ourvalues['message'] = 'Succesfully activated player: %s ' % playerid

        if 'deactivate' in params:
            player.activated = 0
            player.activated_on = datetime.now()
            transaction.commit()
            ourvalues['message'] = 'Succesfully deactivated player: %s ' % playerid


        if 'delete' in params:
            ourvalues['message'] = 'Succesfully delete player: %s ' % playerid



        returnvalue =  self.userlist()
        returnvalue.update(ourvalues)

        return returnvalue
Esempio n. 9
0
    def submit(self):
        params = self.request.params
        import transaction
        session = DBSession()
        ourvalues = {}
        try:
            groupid = params.get('groupid')
            group = session.query(Group).filter(Group.id==groupid).one()
            if 'deletegroup' in params:
                ourvalues['message'] = 'Succesfully removed %s ' % group.name

            if 'addgroup' in params:
                groupname = params.get('groupname')
                guildid = params.get('guildid')
                group = Group(groupname, guildid)
                session.add(group)

                ourvalues['message'] = 'Succesfully added %s ' % groupname
        except:
            pass
        returnvalue =  self.grouplist()
        returnvalue.update(ourvalues)
        return returnvalue
Esempio n. 10
0
    def __call__(self):
        dbsession = DBSession()
        fleets = []
        locationlength = 12
        grouper = ''
        params = None
        params = self.request.params
        if "form.submitted" in self.request.params:
            def url_generator(**kw):
                new_url = update_params(self.request.url, page=kw['page'])
                return new_url
            params = self.request.params
#            if 'group_by' in self.request.params and self.request.params.get('group_by') != '':
            fleets = dbsession.query(Fleet,
                                    func.sum(Fleet.size).label("fleet_sum"),
                                    select(["FROM_UNIXTIME(UNIX_TIMESTAMP(fleet.timestamp))"]).label("average_age"),
                                    select(["FROM_UNIXTIME(UNIX_TIMESTAMP(fleet.detailstimestamp))"]).label("average_detail_age"),
                                    select(["fleet.arrival-(unix_timestamp(now())-unix_timestamp(fleet.timestamp))"]).label("absolute_arrival"),
                                    )
#            else:
#                fleets = dbsession.query(Fleet)

           
            if 'location' in self.request.params and self.request.params.get('location') != '':
                locations = self.request.params.get('location').strip().split(',')
                qrs = []
                for location in locations:
                    qrs.append(Fleet.location.like("%s%%" % location))
                fleets = fleets.filter(or_(*qrs))
            fleets = performFleetFilter(fleets, params)
            ##Grouping
            if 'group_by' in self.request.params and self.request.params.get('group_by') != '':
                grouper = self.request.params.get('group_by')
        #                ('owner-01','Location, Owner'),
        #                ('owner-01','Galaxy, Owner'),
        #                ('owner-02','Galaxy-Group, Owner')
        #                ('blob-01','Location, Guild'),
        #                ('blob-02','Galaxy, Guild'),
        #                ('blob-03','Galaxy-Group, Guild'),
                fleets = fleets.join(Fleet.owner)
                fleets = fleets.join(Player.guild)
                if grouper == 'owner-01':
                    fleets = fleets.group_by(Fleet.location, Fleet.ownerid)
                if grouper == 'owner-02':
                    fleets = fleets.group_by(func.substring(Fleet.location,1,3), Fleet.ownerid)
                    locationlength = 3
                if grouper == 'owner-03':
                    fleets = fleets.group_by(func.substring(Fleet.location,1,2), Fleet.ownerid)
                    locationlength = 2
                if grouper == 'blob-01':
                    fleets = fleets.group_by(Fleet.location, GuildInfo.id)
                if grouper == 'blob-02':
                    fleets = fleets.group_by(func.substring(Fleet.location,1,3), GuildInfo.id)
                    locationlength = 3
                if grouper == 'blob-03':
                    fleets = fleets.group_by(func.substring(Fleet.location,1,2), GuildInfo.id)
                    locationlength = 2
            else:
                fleets = fleets.group_by(Fleet.id)
                
            ##Sorting
            if 'sort_field' in self.request.params and self.request.params.get('sort_field') != '':
                fleets = performFleetSort(fleets, self.request.params)

            ##Limits and such
            per_page = int(self.request.params.get('per_page') or 100)
            fleets = paginate.Page(fleets, page=int(self.request.params.get('page', 1)), items_per_page=per_page, url=url_generator, item_count=fleets.count())
#            import pdb; pdb.set_trace()


        return {"datetime":datetime,
                "grouper":grouper,
                "filters": self.filters,
                "fieldfilters":self.fieldfilters,
                "fleets": fleets,
                "params": params,
                "locationlength":locationlength}
Esempio n. 11
0
    def __call__(self):
        dbsession = DBSession()
        location = "A"
        location = "%s%s" % (location, self.request.matchdict.get("galaxy"))
        location = "%s:%s" % (location, self.request.matchdict.get("region"))
        location = "%s:%s" % (location, self.request.matchdict.get("system"))

        astros = dbsession.query(Location)\
                                .options(lazyload('base.submitter'))\
                                .options(lazyload('fleets.owner'))\
                                .options(lazyload('fleets.updater'))\
                                .options(lazyload('fleets.submitter'))\
                                .filter(Location.location.like("%s%%"%location))
        locationdetail = {}
        fleetlocations = []
#        for base in bases:
            

        astrocolumns = 0
        fleetstrings = {}
        locations = {}
        for astro in astros:

            if astro.base:
                locationdetail[astro.location] = { "owner_id":astro.base.ownerid, "owner_guild_id": astro.base.owner.guild and astro.base.owner.guild.id or -1}

            fleetlocations.append(astro.location)
            if int(astro.location[10]) > astrocolumns:
                astrocolumns = int(astro.location[10])

            fleets = []
            for fleet in astro.fleets:
                locdetail = locationdetail.get(fleet.location, {})
                fleetdetail = fleetstrings.get(fleet.location, {"owner":0, "guild":0, "other":0})
                if fleet.owner.id == locdetail.get("owner_id", -1000):
                    fleetdetail['owner'] = fleetdetail.get('owner',0) + fleet.size
                elif fleet.owner.guild and fleet.owner.guild.id == locdetail.get("owner_guild_id", -1000):
                    fleetdetail['guild'] = fleetdetail.get('guild',0) + fleet.size
                else:
                    fleetdetail['other'] = fleetdetail.get('other',0) + fleet.size
                fleetstrings[fleet.location] = fleetdetail
                fleets.append(fleet)

            locations[astro.location] = {'location':astro.location,
                                         'terrain':astro.terrain.name,
                                         'size': astro.location[11]=='0' and '50' or '30',
                                         'base':astro.base or None,
                                         'fleets': fleets}
            if astro.terrain.name == 'Asteroid':
                locations[astro.location]['size'] = 20;

        
        locations = locations.values()
        locations = sorted(locations, key= lambda k: k['location'])

        returnvalue = {'location':location,
                       'columns':astrocolumns,
                       'locations':locations,
                       'astros':astros,
                       'fleets':fleetstrings,
                       'datetime':datetime}
        returnvalue.update(self.request.matchdict)

        return returnvalue
Esempio n. 12
0
    def __call__(self):
        dbsession = DBSession()
        returnvalue = {'location':None}
        location = "A"
        location = "%s%s" % (location, self.request.matchdict.get("galaxy"))

        regions = {}
        legenda = None
        bases = None
        params = {}

        base_search = False
        fleet_search = False
        
        if "form.base_submitted" in self.request.params:
            base_search = True
            params = self.request.params
        elif "form.fleet_submitted" in self.request.params:
            fleet_search = True
            params = self.request.params
        elif self.request.cookies.get('search','') == 'base':
            base_search = True
            params = self.request.cookies
        elif self.request.cookies.get('search','') == 'fleet':
            fleet_search = True
            params = self.request.cookies

        # .outerjoin(Base).filter(Location.location.like("%s%%"%location))
        if base_search:
            regions = makeLocationDict(dbsession, location, 1, 6, 4, 5, do_base=False)
            bases, legenda, regions = self.processBase(dbsession, params, regions, location,  1, 6)
            label = ''
            cookie_key = ['owner','occupier','jumpgate','agevalue', 'maxagefield']
            cookie_set= False

            if "form.base_submitted" in self.request.params:
                for key in cookie_key:
                    if self.request.params.get(key,''):
                        cookie_set = True
                        self.request.response.set_cookie(key, self.request.params.get(key), max_age=timedelta(days=1), path='/')
                    else:
                        self.request.response.delete_cookie(key)

                    if cookie_set:
                        self.request.response.set_cookie('search', 'base', max_age=timedelta(days=1), path='/')
        elif fleet_search:
            fleets = dbsession.query(func.substring(Fleet.location,1,6).label('location'),\
                    func.count('*').label('fleet_count'), \
                    func.sum(Fleet.size).label("fleet_sum"), \
                    select(["FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(fleet.timestamp)))"]).label("average_age")).\
                    group_by(func.substring(Fleet.location,1,6)).filter(Fleet.location.like("%s%%"%location))
            fleets = performFleetFilter(fleets, self.request.params)
            regions = makeLocationDict(dbsession, location, 1, 6, 4, 5, do_base=False)

            cookie_key = ['owner','size','flying','agevalue', 'maxagefield']
            cookie_set= False

            if "form.fleet_submitted" in self.request.params:
                for key in cookie_key:
                    if self.request.params.get(key,''):
                        cookie_set = True
                        self.request.response.set_cookie(key, self.request.params.get(key), max_age=timedelta(days=1), path='/')
                    else:
                        self.request.response.delete_cookie(key)

                    if cookie_set:
                        self.request.response.set_cookie('search', 'fleet', max_age=timedelta(days=1), path='/')

            min_count = 1
            max_count = 1000000
            for fleet_location, fleet_count, fleet_sum, fleet_age in fleets:
                fleet_sum = fleet_sum / 1000
                row = int(fleet_location[4])
                col = int(fleet_location[5])
                location_info = regions[row][col]
                location_info['fleet_count'] = fleet_count
                location_info['fleet_sum'] = fleet_sum
#                if fleet_sum > max_count:
#                    max_count = fleet_sum
#                if fleet_sum < min_count or min_count == None:
#                    min_count = fleet_sum
#                location_info['base_age'] = getCountColor(base_count)
                regions[row][col] = location_info
            legenda = getCountLegenda(min=min_count,max=max_count, single='fleet', plural='fleets')

            for fleet_location, fleet_count, fleet_sum, fleet_age in fleets:
                row = int(fleet_location[4])
                col = int(fleet_location[5])
                location_info = regions[row][col]
                location_info['base_age'] = getCountColor(math.trunc(fleet_sum), min=min_count,max=max_count, single='fleet', plural='fleets')
            label = 'Fleet sum:'
        else:
            regions = makeLocationDict(dbsession, location, 1, 6, 4, 5)
            label = 'Avg. age'
            legenda = getAgeLegenda()


        returnvalue = {'base_filters': self.basefilters,
                       'fleet_filters': self.fleetfilters,
                       'label': label,
                       'params': params,
                       'bases':bases,
                       'location':location,
                       'regions': regions,
                       'legenda': legenda,
                       'datetime':datetime}
        returnvalue.update(self.request.matchdict)
        return returnvalue
Esempio n. 13
0
    def __call__(self):

        """ login view callable """

        # convenient method to set Cache-Control and Expires headers
        self.request.response.cache_expires = 0

        dbsession = DBSession()

        params = self.request.params
        login_url = route_url('login', self.request)
        message = ''

        # playerid, password from cookie
        playerid = ''
        password = ''
        passwordFromCookie = False
        lc = self.request.cookies.get('cis_login_credentials', '')
        if lc:
            lc = lc.split('|')
            if len(lc) == 3:
                passwordFromCookie = True
                playerid = lc[0]
                password = lc[1]

        activeUser = User()
        activeUser.playerid = playerid
        activeUser.password = password

        user = None
        errors = {}
        passwordOk = False
        referrer = self.request.url

        if referrer == login_url:
            referrer = '/'

        came_from = self.request.params.get('came_from', referrer)
        url = came_from
        logged_in = authenticated_userid(self.request)
        headers = ''

        initial_login = not logged_in

        storeplayeridPwd = params.get('remember', '')

        # if already logged in and requesting this page, redirect to forbidden

        if logged_in:
            message = 'You do not have the required permissions to see this page.'
            return dict(
                    message=message,
                    url=url,
                    came_from=came_from,
                    password=password,
                    user=activeUser,
                    headers=headers,
                    errors=errors,
                    logged_in=logged_in,
                    remember=storeplayeridPwd
                    )
        # check whether we are asked to do an autologin (from pwdreset.py)
        autologin = 0 #self.request.session.pop_flash(queue='autologin')

        # 'SECURITY RISK'
        forcelogin = lc and self.request.params.get('forcelogin', '')
        if forcelogin or autologin or 'form.submitted' in params:

            if autologin:
                autologin = autologin[0].split('|')
                playerid = autologin[0]
                password = autologin[1] #encrypted
            elif forcelogin:
                pass
            else:
                playerid = params['playerid']
                # when we get a password from a cookie, we already receive it encrypted. If not, encrypt it here
                password = (passwordFromCookie and password) or params['password']

            if not password:
                errors['password'] = "******"
            else:
                # if autologin, we already receive it encrypted. If not, encrypt it here
                password = ((forcelogin or autologin) and password) or hashlib.md5(params['password']).hexdigest()

            if not playerid:
                errors['playerid'] = "Enter your player id"

            if playerid and password:
                user = dbsession.query(User).filter_by(playerid=playerid).first()

                if user:
                    passwordOk = (user.password == password)
                if not user:
                    message = 'You do not have a CIS account'
                elif user.banned:
                    message = 'Your account has been banned.'
                elif not user.activated:
                    message = 'Your account has not yet been activated'
                elif not passwordOk:
                    message = 'Your account/password do not match' 
                else:
                    
                    # READY TO LOGIN, SOME FINAL CHECKS
                    now = datetime.now()

                    headers = remember(self.request, user.playerid)
                    last_login = now.strftime('%Y-%m-%d %H:%M:%S')
                    user.last_web = last_login

                    response = HTTPFound()
                    user.last_login = last_login
                    response.headers = headers

                    response.content_type = 'text/html'
                    response.charset = 'UTF-8' 
                    if storeplayeridPwd:
                        cookie_val = '%s|%s' % (playerid, password)
                        response.set_cookie('cis_login_credentials', cookie_val, max_age=timedelta(days=365), path='/')

                    response.location = came_from
                    if (not forcelogin) and (not storeplayeridPwd):
                        response.delete_cookie('cis_login_credentials')

                    response.cache_control = 'no-cache'
                    return response

            activeUser.playerid = playerid

        storeplayeridPwd = self.request.cookies.get('cis_login_credentials') and '1' or ''
        return dict(
                    message=message,
                    url=url,
                    came_from=came_from,
                    password=password,
                    user=activeUser,
                    headers=headers,
                    errors=errors,
                    logged_in=logged_in,
                    remember=storeplayeridPwd
                    )