Beispiel #1
0
 def tick(self, message, user, params):
     tick = Updates.load(params.group(1)) or Updates.current_tick()
     if isinstance(tick, Updates): # We have that tick
         message.reply(str(tick))
     elif tick == 0:               # We don't have any ticks
         ticktime = GameSetup.getint("round_start_time") + (int(params.group(1))-1)*GameSetup.getint("tick_speed")
         tdiff = int(ticktime - time.time())
         tdelta = abs(tdiff / 86400)
         retstr  = " %sd" % tdelta if tdelta else ""
         tdelta = (tdiff % 86400) / 3600
         retstr += " %sh" % tdelta if tdelta else ""
         tdelta = (tdiff % 3600) / 60
         retstr += " %sm" % tdelta if tdelta else ""
         retstr = "Tick %s %s expected to happen%s%s%s - %s" % (params.group(1), "is" if tdiff >= 0 else "was", " in" if tdiff >= 0 else "", retstr, " ago" if tdiff < 0 else "", datetime.utcfromtimestamp(float(ticktime)).strftime("%a %d/%m %H:%M UTC"))
         message.reply(retstr)
     else:                         # We have some ticks, but not that one
         diff = int(params.group(1)) - tick
         now = datetime.utcnow()
         tick_speed = GameSetup.getint("tick_speed")
         tdiff = timedelta(seconds=tick_speed*diff)-timedelta(minutes=now.minute%(tick_speed/60))
         retstr  = "%sd " % abs(tdiff.days) if tdiff.days else ""
         retstr += "%sh " % abs(tdiff.seconds/3600) if tdiff.seconds/3600 else ""
         retstr += "%sm " % abs(tdiff.seconds%3600/60) if tdiff.seconds%3600/60 else ""
             
         if diff == 1:
             retstr = "Next tick is %s (in %s" % (params.group(1), retstr)
         elif diff > 1:
             retstr = "Tick %s is expected to happen in %s ticks (in %s" % (params.group(1), diff, retstr)
         elif diff <= 0:
             retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (params.group(1), -diff, retstr)
         
         ticktime = now + tdiff
         retstr += " - %s)" % (ticktime.strftime("%a %d/%m %H:%M UTC"),)
         message.reply(retstr)
Beispiel #2
0
    def tick(self, message, user, params):
        tick = Updates.load(params.group(1)) or Updates.current_tick()
        if tick is None:
            message.reply("Ticks haven't started yet, go back to masturbating.")
        elif isinstance(tick, Updates):
            message.reply(str(tick))
        else:
            diff = int(params.group(1)) - tick
            now = datetime.utcnow()
            tick_length = PA.getint("numbers", "tick_length")
            tdiff = timedelta(seconds=tick_length * diff) - timedelta(minutes=now.minute % (tick_length / 60))
            seconds = 0
            retstr = "%sd " % abs(tdiff.days) if tdiff.days else ""
            retstr += "%sh " % abs(tdiff.seconds / 3600) if tdiff.seconds / 3600 else ""
            retstr += "%sm " % abs(tdiff.seconds % 3600 / 60) if tdiff.seconds % 3600 / 60 else ""

            if diff == 1:
                retstr = "Next tick is %s (in %s" % (params.group(1), retstr)
            elif diff > 1:
                retstr = "Tick %s is expected to happen in %s ticks (in %s" % (params.group(1), diff, retstr)
            elif diff <= 0:
                retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (
                    params.group(1),
                    -diff,
                    retstr,
                )

            time = now + tdiff
            retstr += " - %s)" % (time.strftime("%a %d/%m %H:%M"),)
            message.reply(retstr)
Beispiel #3
0
 def tick(self, message, user, params):
     tick = Updates.load(params.group(1)) or Updates.current_tick()
     if tick is None:
         message.reply("Ticks haven't started yet, go back to masturbating.")
     elif isinstance(tick, Updates):
         message.reply(str(tick))
     else:
         diff = int(params.group(1)) - tick
         now = datetime.utcnow()
         tick_length = PA.getint("numbers", "tick_length")
         tdiff = timedelta(seconds=tick_length*diff)-timedelta(minutes=now.minute%(tick_length/60))
         seconds = 0
         retstr  = "%sd " % abs(tdiff.days) if tdiff.days else ""
         retstr += "%sh " % abs(tdiff.seconds/3600) if tdiff.seconds/3600 else ""
         retstr += "%sm " % abs(tdiff.seconds%3600/60) if tdiff.seconds%3600/60 else ""
             
         if diff == 1:
             retstr = "Next tick is %s (in %s" % (params.group(1), retstr)
         elif diff > 1:
             retstr = "Tick %s is expected to happen in %s ticks (in %s" % (params.group(1), diff, retstr)
         elif diff <= 0:
             retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (params.group(1), -diff, retstr)
         
         time = now + tdiff
         retstr += " - %s)" % (time.strftime("%a %d/%m %H:%M"),)
         message.reply(retstr)
Beispiel #4
0
    def execute(self, request, user, x, y, z, fleets):
        tick = Updates.midnight_tick()
        week = Updates.week_tick()

        planet = Planet.load(x, y, z)
        if planet is None:
            return HttpResponseRedirect(reverse("planet_ranks"))
        ph = planet.history(tick)

        Q = session.query(FleetScan, Planet, Alliance)
        Q = Q.join(FleetScan.target)
        Q = Q.outerjoin(Planet.intel).outerjoin(Intel.alliance)
        Q = Q.filter(FleetScan.owner == planet)
        Q = Q.order_by(desc(FleetScan.landing_tick))
        if not fleets:
            Q = Q.filter(FleetScan.landing_tick >= week)
        outgoing = Q.all()

        Q = session.query(FleetScan, Planet, Alliance)
        Q = Q.join(FleetScan.owner)
        Q = Q.outerjoin(Planet.intel).outerjoin(Intel.alliance)
        Q = Q.filter(FleetScan.target == planet)
        Q = Q.order_by(desc(FleetScan.landing_tick))
        if not fleets:
            Q = Q.filter(FleetScan.landing_tick >= week)
        incoming = Q.all()

        scan = planet.scan("A") or planet.scan("U")

        return render("planet.tpl", request, planet=planet, ph=ph, scan=scan, outgoing=outgoing, incoming=incoming)
Beispiel #5
0
    def parse_D(self, scan_id, scan, page):
        devscan = scan.devscan = DevScan()

        m=re.search("""
            <tr><td[^>]*>Light\s+Factory</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Medium\s+Factory</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Heavy\s+Factory</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Wave\s+Amplifier</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Wave\s+Distorter</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Metal\s+Refinery</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Crystal\s+Refinery</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Eonium\s+Refinery</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Research\s+Laboratory</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Finance\s+Centre</td><td[^>]*>(\d*)</td></tr>\s*
            <tr><td[^>]*>Security\s+Centre</td><td[^>]*>(\d*)</td></tr>
        """, page,re.VERBOSE)

        devscan.light_factory = m.group(1)
        devscan.medium_factory = m.group(2)
        devscan.heavy_factory = m.group(3)
        devscan.wave_amplifier = m.group(4)
        devscan.wave_distorter = m.group(5)
        devscan.metal_refinery = m.group(6)
        devscan.crystal_refinery = m.group(7)
        devscan.eonium_refinery = m.group(8)
        devscan.research_lab = m.group(9)
        devscan.finance_centre = m.group(10)
        devscan.security_centre = m.group(11)

        m = re.search("""
            <tr><td[^>]*>Space\s+Travel</td><td[^>]*>(\d+)</td></tr>\s*
            <tr><td[^>]*>Infrastructure</td><td[^>]*>(\d+)</td></tr>\s*
            <tr><td[^>]*>Hulls</td><td[^>]*>(\d+)</td></tr>\s*
            <tr><td[^>]*>Waves</td><td[^>]*>(\d+)</td></tr>\s*
            <tr><td[^>]*>Core\s+Extraction</td><td[^>]*>(\d+)</td></tr>\s*
            <tr><td[^>]*>Covert\s+Ops</td><td[^>]*>(\d+)</td></tr>\s*
            <tr><td[^>]*>Asteroid\s+Mining</td><td[^>]*>(\d+)</td></tr>
        """, page,re.VERBOSE)

        devscan.travel = m.group(1)
        devscan.infrastructure = m.group(2)
        devscan.hulls = m.group(3)
        devscan.waves = m.group(4)
        devscan.core = m.group(5)
        devscan.covert_op = m.group(6)
        devscan.mining = m.group(7)

        session.commit()

        if scan.planet.intel is None:
            scan.planet.intel = Intel()
        if (scan.planet.intel.dists < devscan.wave_distorter) or (scan.tick == Updates.current_tick()):
            scan.planet.intel.dists = devscan.wave_distorter
            session.commit()
            scanlog("Updating planet-intel-dists")
        if (scan.planet.intel.amps < devscan.wave_amplifier) or (scan.tick == Updates.current_tick()):
            scan.planet.intel.amps = devscan.wave_amplifier
            session.commit()
            scanlog("Updating planet-intel-amps")
Beispiel #6
0
 def tick(self, message, user, params):
     tick = Updates.load(params.group(1)) or Updates.current_tick()
     if tick is None:
         message.reply("Ticks haven't started yet, go back to masturbating.")
     elif isinstance(tick, Updates):
         message.reply(str(tick))
     else:
         diff = int(params.group(1)) - tick
         now = datetime.utcnow()
         seconds = 0
         retstr = ""
         if diff > 0:
             
             if diff > 24:
                 days = (diff-1)/24
                 seconds += days*24*60*60
                 retstr += "%sd " % (days,)
             
             if diff > 1:
                 hours = (diff-1)%24
                 seconds += hours*60*60
                 retstr += "%sh " % (hours,)
             
             mins = 60 - now.minute
             seconds += mins *60
             retstr += "%sm" % (mins,)
             
             if diff == 1:
                 retstr = "Next tick is %s (in %s" % (params.group(1), retstr,)
             else:
                 retstr = "Tick %s is expected to happen in %s ticks (in %s" % (params.group(1), diff, retstr,)
         
         elif diff < 0:
             
             if diff < -23:
                 days = (-diff)/24
                 seconds -= days*24*60*60
                 retstr += "%sd " % (days,)
                 
             if diff < -1:
                 hours = (-diff)%24
                 seconds -= hours*60*60
                 retstr += "%sh " % (hours,)
                 
             mins = now.minute
             seconds -= mins*60
             retstr += "%sm" % (mins,)
             
             if diff == -1:
                 retstr = "Last tick was %s (%s ago" % (params.group(1), retstr,)
             else:
                 retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (params.group(1), -diff, retstr,)
         
         time = now + timedelta(seconds=seconds)
         retstr += " - %s)" % (time.strftime("%a %d/%m %H:%M"),)
         message.reply(retstr)
Beispiel #7
0
 def list(self, message, user, params):
     Q = session.query(Attack)
     if user.access < (Config.getint("Access",  "hc") if "hc" in Config.options("Access") else 1000): # Hide attacks until they are active, unless the user has access
         Q = Q.filter(Attack.landtick <= Updates.current_tick() + Config.getint("Misc", "attactive"))
     Q = Q.filter(Attack.landtick + Attack.waves >= Updates.current_tick()) # Hide attacks one tick after the last wave has landed
     Q = Q.order_by(asc(Attack.id))
     
     replies = []
     for attack in Q:
         replies.append("(%d LT: %d %s)" %(attack.id,attack.landtick,attack.comment,))
     
     reply = "Open attacks: " + " ".join(replies)
     message.reply(reply)
Beispiel #8
0
def base_context(request):
    context = {"name"   : Config.get("Alliance", "name"),
               "slogan" : Config.get("Alliance", "name"),
               "tick"   : Updates.current_tick(),
               "update" : Updates.load(),
               }
    if getattr(request, "user", None) is not None:
        context["user"] = request.user
        context["menu"] = menu.generate(request.user)
    if getattr(request, "session", None) is not None:
        slogan, count = Slogan.search("")
        if slogan is not None:
            context["slogan"] = str(slogan)
    return context
Beispiel #9
0
    def execute(self, request, user, page="1", sort="score"):
        page = int(page)
        offset = (page - 1) * 50
        order = {
            "score": (asc(Galaxy.score_rank),),
            "value": (asc(Galaxy.value_rank),),
            "size": (asc(Galaxy.size_rank),),
            "xp": (asc(Galaxy.xp_rank),),
        }
        if sort not in order.keys():
            sort = "score"
        order = order.get(sort)

        tick = Updates.midnight_tick()

        Q = session.query(Galaxy, GalaxyHistory)
        Q = Q.outerjoin((GalaxyHistory, and_(Galaxy.id == GalaxyHistory.id, GalaxyHistory.tick == tick)))
        Q = Q.filter(Galaxy.active == True)

        count = Q.count()
        pages = count / 50 + int(count % 50 > 0)
        pages = range(1, 1 + pages)

        for o in order:
            Q = Q.order_by(o)
        Q = Q.limit(50).offset(offset)
        return render("galaxies.tpl", request, galaxies=Q.all(), offset=offset, pages=pages, page=page, sort=sort)
Beispiel #10
0
def rollback(message):
    """Rollback to a given tick. Tick must be repeated for confirmation."""
    
    msg = message.get_msg().split()[1:]
    if len(msg) != 2:
        message.reply("rollback <tick> <tick>")
        return
    if msg[0] != msg[1]:
        message.reply("Ticks must match!")
        return
    if not msg[0].isdigit():
        message.reply("Ticks should be numeric.")
        return
    if int(msg[0]) > Updates.current_tick():
        message.reply("Timetravel module not installed. Cannot rollback to a future tick.")
        return

    session.execute(text("DELETE FROM updates WHERE id > %s;" % (msg[0])))
    session.execute(text("DELETE FROM planet_exiles WHERE tick > %s;" % (msg[0])))
    session.execute(text("DELETE FROM planet_idles WHERE tick > %s;" % (msg[0])))
    session.execute(text("DELETE FROM planet_value_drops WHERE tick > %s;" % (msg[0])))
    session.execute(text("DELETE FROM planet_landings WHERE tick > %s;" % (msg[0])))
    session.execute(text("DELETE FROM planet_landed_on WHERE tick > %s;" % (msg[0])))
    session.execute(text("DELETE from galaxy_history where tick > %s;" % (msg[0])))
    session.execute(text("DELETE from planet_history where tick > %s;" % (msg[0])))
    session.execute(text("DELETE from alliance_history where tick > %s;" % (msg[0])))
    session.execute(text("DELETE from cluster_history where tick > %s;" % (msg[0])))

    session.commit()
    message.reply("Rollback complete. Bot will update at next tick.")
Beispiel #11
0
 def links(self, message, user, params):
     Q = session.query(Request)
     Q = Q.filter(Request.tick > Updates.current_tick() - 5)
     Q = Q.filter(Request.active == True)
     Q = Q.order_by(asc(Request.id))
     
     message.reply(" ".join(map(lambda request: "[%s: %s]" % (request.id, request.link,), Q[:5])))
Beispiel #12
0
 def list(self, message, user, params):
     Q = session.query(Request)
     Q = Q.filter(Request.tick > Updates.current_tick() - 5)
     Q = Q.filter(Request.active == True)
     Q = Q.order_by(asc(Request.id))
     
     message.reply(" ".join(map(lambda request: "[%s: %s %s:%s:%s]" % (request.id, request.scantype, request.target.x, request.target.y, request.target.z,), Q.all())))
Beispiel #13
0
 def execute(self, request, user, page="1", sort="score"):
     page = int(page)
     offset = (page - 1)*50
     order =  {"score" : (asc(Alliance.score_rank),),
               "size"  : (asc(Alliance.size_rank),),
               "avg_score" : (asc(Alliance.score_avg_rank),),
               "avg_size"  : (asc(Alliance.size_avg_rank),),
               "members"   : (asc(Alliance.members_rank),),
               } 
     if sort not in order.keys():
         sort = "score"
     order = order.get(sort)
     
     tick = Updates.midnight_tick()
     
     Q = session.query(Alliance, AllianceHistory)
     Q = Q.outerjoin((AllianceHistory, and_(Alliance.id == AllianceHistory.id, AllianceHistory.tick == tick)))
     Q = Q.filter(Alliance.active == True)
     
     count = Q.count()
     pages = count/50 + int(count%50 > 0)
     pages = range(1, 1+pages)
     
     for o in order:
         Q = Q.order_by(o)
     Q = Q.limit(50).offset(offset)
     return render("alliances.tpl", request, alliances=Q.all(), offset=offset, pages=pages, page=page, sort=sort)
Beispiel #14
0
    def execute(self, request, user, message=None, planet=None):
        tick = Updates.current_tick()

        Q = session.query(Request)
        Q = Q.filter(Request.user == user)
        Q = Q.filter(Request.tick > tick - 5)
        Q = Q.filter(Request.active == True)
        Q = Q.order_by(asc(Request.id))
        open = Q.all()

        Q = session.query(Scan)
        Q = Q.join(Request.scan)
        Q = Q.filter(Request.user == user)
        Q = Q.filter(Request.tick > tick - 24)
        Q = Q.filter(Request.scan != None)
        Q = Q.order_by(desc(Request.id))
        completed = Q.all()

        Q = session.query(Scan)
        Q = Q.filter(Scan.scanner == user)
        Q = Q.order_by(desc(Scan.id))
        scans = Q[:25]

        return render("scans/scans.tpl",
                      request,
                      anonscans=Config.getboolean("Misc", "anonscans"),
                      types=Request._requestable,
                      open=open,
                      completed=completed,
                      scans=scans,
                      message=message,
                      planet=planet)
Beispiel #15
0
    def execute(self, message, user, params):

        tick = Updates.current_tick() + int(params.group(1) or 1)
        replies = []

        Q = session.query(Galaxy.x, Galaxy.y, count())
        Q = Q.join(Target.planet)
        Q = Q.join(Planet.galaxy)
        Q = Q.filter(Planet.active == True)
        Q = Q.filter(Target.tick >= tick)
        Q = Q.group_by(Galaxy.x, Galaxy.y)
        result = Q.all()
        prev = []
        for x, y, bitches in result:
            prev.append("%s:%s(%s)" % (x, y, bitches))
        replies.append("Active bookings: " + ", ".join(prev))

        Q = session.query(Alliance.name, count())
        Q = Q.join(Target.planet)
        Q = Q.outerjoin(Planet.intel)
        Q = Q.outerjoin(Intel.alliance)
        Q = Q.filter(Planet.active == True)
        Q = Q.filter(Target.tick >= tick)
        Q = Q.group_by(Alliance.name)
        result = Q.all()
        prev = []
        for name, bitches in result:
            prev.append("%s (%s)" % (name or "Unknown", bitches))
        replies.append("Active bitches: " + ", ".join(prev))

        if len(replies) < 1:
            replies.append(
                "No active bookings. This makes %s sad. Please don't make %s sad."
                % ((Config.get("Connection", "nick"), ) * 2))
        message.reply("\n".join(replies))
Beispiel #16
0
    def execute(self, message, user, params):
        
        count = self.short2num(params.group(1) or "1")
        name = params.group(2)

        ship = Ship.load(name=name)
        if ship is None:
            message.alert("No Ship called: %s" % (name,))
            return
        
        Q = session.query(User, UserFleet)
        Q = Q.join(User.fleets)
        Q = Q.filter(User.active == True)
        Q = Q.filter(User.access >= Config.getint("Access", "member"))
        Q = Q.filter(UserFleet.ship == ship)
        Q = Q.filter(UserFleet.ship_count >= count)
        Q = Q.filter(User.fleetcount > 0)
        Q = Q.order_by(desc(UserFleet.ship_count))
        result = Q.all()
        
        if len(result) < 1:
            message.reply("There are no planets with free fleets and at least %s ships matching '%s'"%(self.num2short(count),ship.name))
            return
        
        tick = Updates.current_tick()
        reply = "Fleets matching query: "
        reply+= " // ".join(map(lambda (u, x): "%s(%s) %s: %s %s ((%s))"%(u.name,u.fleetupdated-tick,u.fleetcount,self.num2short(x.ship_count),ship.name,u.fleetcomment),result))
        message.reply(reply)
Beispiel #17
0
    def new(self, message, user, params):
        tick = Updates.current_tick()
        comment = params.group(3) or ""
        when = int(params.group(1))
        if when < PA.getint("numbers", "protection"):
            eta = when
            when += tick
        elif when <= tick:
            message.alert(
                "Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick)
            )
            return
        else:
            eta = when - tick
        if when > 32767:
            when = 32767

        attack = Attack(landtick=when, comment=comment)
        session.add(attack)

        for coord in re.findall(loadable.coord, params.group(2)):
            if not coord[4]:
                galaxy = Galaxy.load(coord[0], coord[2])
                if galaxy:
                    attack.addGalaxy(galaxy)

            else:
                planet = Planet.load(coord[0], coord[2], coord[4])
                if planet:
                    attack.addPlanet(planet)

        session.commit()
        message.reply(str(attack))
Beispiel #18
0
    def execute(self, message, user, params):

        count = self.short2num(params.group(1) or "1")
        name = params.group(2)

        ship = Ship.load(name=name)
        if ship is None:
            message.alert("No Ship called: %s" % (name, ))
            return

        Q = session.query(User, UserFleet)
        Q = Q.join(User.fleets)
        Q = Q.filter(User.active == True)
        Q = Q.filter(User.access >= Config.getint("Access", "member"))
        Q = Q.filter(UserFleet.ship == ship)
        Q = Q.filter(UserFleet.ship_count >= count)
        Q = Q.filter(User.fleetcount > 0)
        Q = Q.order_by(desc(UserFleet.ship_count))
        result = Q.all()

        if len(result) < 1:
            message.reply(
                "There are no planets with free fleets and at least %s ships matching '%s'"
                % (self.num2short(count), ship.name))
            return

        tick = Updates.current_tick()
        reply = "Fleets matching query: "
        reply += ", ".join(
            map(
                lambda (u, x): "%s(%s) %s: %s %s" %
                (u.name, u.fleetupdated - tick, u.fleetcount,
                 self.num2short(x.ship_count), ship.name), result))
        message.reply(reply)
Beispiel #19
0
 def execute(self, request, user, page="1", sort="score", race="all"):
     page = int(page)
     offset = (page - 1)*50
     order =  {"score" : (asc(Planet.score_rank),),
               "value" : (asc(Planet.value_rank),),
               "size"  : (asc(Planet.size_rank),),
               "xp"    : (asc(Planet.xp_rank),),
               "race"  : (asc(Planet.race), asc(Planet.size_rank),),
               }
     if sort not in order.keys():
         sort = "score"
     order = order.get(sort)
     
     tick = Updates.midnight_tick()
     
     Q = session.query(Planet, PlanetHistory, Intel.nick, Alliance.name)
     Q = Q.outerjoin(Planet.intel)
     Q = Q.outerjoin(Intel.alliance)
     Q = Q.outerjoin((PlanetHistory, and_(Planet.id == PlanetHistory.id, PlanetHistory.tick == tick)))
     Q = Q.filter(Planet.active == True)
     
     if race.lower() in PA.options("races"):
         Q = Q.filter(Planet.race.ilike(race))
     else:
         race = "all"
     
     count = Q.count()
     pages = count/50 + int(count%50 > 0)
     pages = range(1, 1+pages)
     
     for o in order:
         Q = Q.order_by(o)
     Q = Q.limit(50).offset(offset)
     return render("planets.tpl", request, planets=Q.all(), offset=offset, pages=pages, page=page, sort=sort, race=race)
Beispiel #20
0
 def execute(self, message, user, params):
     
     tick = Updates.current_tick() + (params.group(1) or 1)
     replies = []
     
     Q = session.query(Galaxy.x, Galaxy.y, count())
     Q = Q.join(Target.planet)
     Q = Q.join(Planet.galaxy)
     Q = Q.filter(Planet.active == True)
     Q = Q.filter(Target.tick >= tick)
     Q = Q.group_by(Galaxy.x, Galaxy.y)
     result = Q.all()
     prev = []
     for x, y, bitches in result:
         prev.append("%s:%s(%s)"%(x,y,bitches))
     replies.append("Active bookings: " + ", ".join(prev))
     
     Q = session.query(Alliance.name, count())
     Q = Q.join(Target.planet)
     Q = Q.outerjoin(Planet.intel)
     Q = Q.outerjoin(Intel.alliance)
     Q = Q.filter(Planet.active == True)
     Q = Q.filter(Target.tick >= tick)
     Q = Q.group_by(Alliance.name)
     result = Q.all()
     prev = []
     for name, bitches in result:
         prev.append("%s (%s)"%(name or "Unknown", bitches))
     replies.append("Active bitches: " + ", ".join(prev))
     
     if len(replies) < 1:
         replies.append("No active bookings. This makes %s sad. Please don't make %s sad." %((Config.get("Connection","nick"),)*2))
     message.reply("\n".join(replies))
Beispiel #21
0
 def execute(self, request, user):
     if user.planet is not None:
         tick = Updates.midnight_tick()
         ph = user.planet.history(tick)
     else:
         ph = None
     return render("index.tpl", request, planet=user.planet, ph=ph)
Beispiel #22
0
 def execute(self, request, user, id, message=None):
     attack = Attack.load(id)
     if attack is None or not attack.active:
         return HttpResponseRedirect(reverse("attacks"))
     
     waves = xrange(attack.landtick, attack.landtick + Attack._waves)
     show_jgps = attack.landtick <= Updates.current_tick() + Attack._show_jgp_ticks
     
     group = []
     scans = []
     for planet in attack.planets:
         group.append((planet, [], [],))
         if planet.scan("P"):
             group[-1][1].append(planet.scan("P"))
             scans.append(planet.scan("P"))
         
         if planet.scan("D"):
             group[-1][1].append(planet.scan("D"))
             scans.append(planet.scan("D"))
         
         if planet.scan("A") or planet.scan("U"):
             group[-1][1].append(planet.scan("A") or planet.scan("U"))
             scans.append(planet.scan("A") or planet.scan("U"))
         
         if show_jgps and planet.scan("J"):
             group[-1][1].append(planet.scan("J"))
             scans.append(planet.scan("J"))
         
         bookings = dict([(target.tick, target,) for target in planet.bookings.filter(Target.tick.between(attack.landtick, attack.landtick+4))])
         for tick in waves:
             group[-1][2].append((tick, bookings.get(tick) or (False if show_jgps else None),))
     
     return render("attack.tpl", request, attack=attack, message=message, waves=waves, group=group, scans=scans)
Beispiel #23
0
 def land(self, message, user, params):
     id = int(params.group(1))
     attack = Attack.load(id)
     if attack is None:
         message.alert("No attack exists with id %d" %(id))
         return
     
     tick = Updates.current_tick()
     when = int(params.group(2))
     
     if when == 0:
         session.delete(attack)
         session.commit()
         message.reply("Deleted Attack %d LT: %d | %s" %(attack.id,attack.landtick,attack.comment,))
         return
     
     if when < PA.getint("numbers", "protection"):
         eta = when
         when += tick
     elif when <= tick:
         message.alert("Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
         return
     else:
         eta = when - tick
     if when > 32767:
         when = 32767
     
     old = attack.landtick
     attack.landtick = when
     
     session.commit()
     message.reply("Changed LT for attack %d from %d to %d"%(id,old,when))
Beispiel #24
0
 def execute(self, request, user, x, y, z, fleets=False):
     week = Updates.week_tick()
     
     planet = Planet.load(x,y,z)
     if planet is None:
         return HttpResponseRedirect(reverse("planet_ranks"))
     
     Q = session.query(FleetScan, Planet, Alliance)
     Q = Q.join(FleetScan.target)
     Q = Q.outerjoin(Planet.intel).outerjoin(Intel.alliance)
     Q = Q.filter(FleetScan.owner == planet)
     Q = Q.order_by(desc(FleetScan.landing_tick))
     if not fleets:
         Q = Q.filter(FleetScan.landing_tick >= week)
     outgoing = Q.all()
     
     Q = session.query(FleetScan, Planet, Alliance)
     Q = Q.join(FleetScan.owner)
     Q = Q.outerjoin(Planet.intel).outerjoin(Intel.alliance)
     Q = Q.filter(FleetScan.target == planet)
     Q = Q.order_by(desc(FleetScan.landing_tick))
     if not fleets:
         Q = Q.filter(FleetScan.landing_tick >= week)
     incoming = Q.all()
     
     scan = planet.scan("A") or planet.scan("U")
     
     return render("iplanet.tpl", request, planet=planet, scan=scan, outgoing=outgoing, incoming=incoming)
Beispiel #25
0
    def execute(self, request, user, x, y, z, type, dists):
        from Arthur.views.scans.list import scans
        tick = Updates.current_tick()
        type = type.upper()

        planet = Planet.load(x, y, z)
        if planet is None:
            return scans.execute(request,
                                 user,
                                 message="No planet with coords %s:%s:%s" % (
                                     x,
                                     y,
                                     z,
                                 ))

        dists = int(dists or 0)
        req = Request(target=planet, scantype=type, dists=dists)
        user.requests.append(req)
        session.commit()

        push("request", request_id=req.id, mode="request")

        return scans.execute(request,
                             user,
                             message="Requested a %s Scan of %s:%s:%s" % (
                                 req.type,
                                 x,
                                 y,
                                 z,
                             ),
                             planet=planet)
Beispiel #26
0
 def current(self, message, user, params):
     tick = Updates.load()
     if tick is None:
         message.reply(
             "Ticks haven't started yet, go back to masturbating.")
     else:
         message.reply(str(tick))
Beispiel #27
0
def base_context(request):
    context = {
        "name": Config.get("Alliance", "name"),
        "slogan": Config.get("Alliance", "name"),
        "tick": Updates.current_tick(),
        "update": Updates.load(),
        "graphs": Config.get("Misc", "graphing") != "disabled",
    }
    if getattr(request, "user", None) is not None:
        context["user"] = request.user
        context["menu"] = menu.generate(request.user)
    if getattr(request, "session", None) is not None:
        slogan, count = Slogan.search("")
        if slogan is not None:
            context["slogan"] = str(slogan)
    return context
Beispiel #28
0
 def execute(self, request, user, id, x, y, z, when):
     planet = Planet.load(x,y,z)
     if planet is None:
         return self.attack(request, user, id, "No planet with coords %s:%s:%s" %(x,y,z,))
     
     tick = Updates.current_tick()
     when = int(when)
     if when < PA.getint("numbers", "protection"):
         eta = when
         when += tick
     elif when <= tick:
         return self.attack(request, user, id, "Can not book targets in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
     else:
         eta = when - tick
     if when > 32767:
         when = 32767        
     
     if planet.intel and planet.alliance and planet.alliance.name == Config.get("Alliance","name"):
         return self.attack(request, user, id, "%s:%s:%s is %s in %s. Quick, launch before they notice!" % (x,y,z, planet.intel.nick or 'someone', Config.get("Alliance","name"),))
     
     try:
         planet.bookings.append(Target(user=user, tick=when))
         session.commit()
     except IntegrityError:
         session.rollback()
         target = planet.bookings.filter(Target.tick == when).first()
         if target is not None:
             return self.attack(request, user, id, "Target %s:%s:%s is already booked for landing tick %s by user %s" % (x,y,z, when, target.user.name,))
     else:
         return self.attack(request, user, id, "Booked landing on %s:%s:%s tick %s (eta %s) for user %s" % (x,y,z, when, (when-tick), user.name,))
     
     return self.attack(request, user, id)
Beispiel #29
0
    def execute(self, message, user, params):

        eta, land_tick = params.groups()
        land_tick = int(land_tick)

        if eta.lower() in self.class_eta.keys():
            eta = self.class_eta[eta.lower()]
        else:
            try:
                eta = int(eta)
            except ValueError:
                message.alert("Invalid class or eta '%s'" % (eta, ))
                return

        current_tick = Updates.current_tick()

        current_time = datetime.datetime.utcnow()
        tick_length = PA.getint("numbers", "tick_length")
        launch_tick = land_tick - eta
        launch_time = current_time + datetime.timedelta(
            seconds=tick_length *
            (launch_tick - current_tick + 1)) - datetime.timedelta(
                minutes=current_time.minute % (tick_length / 60) + 5)
        prelaunch_tick = land_tick - eta + 1
        prelaunch_mod = launch_tick - current_tick

        message.reply(
            "eta %d landing pt %d (currently %d) must launch at pt %d (%s), or with prelaunch tick %d (currently %+d)"
            % (eta, land_tick, current_tick, launch_tick,
               (launch_time.strftime("%m-%d %H:%M")), prelaunch_tick,
               prelaunch_mod))
Beispiel #30
0
    def execute(self, message, user, params):
        
        fleetcount = int(params.group(1))
        comment = params.group(2)
        reply = ""

        if user.planet:
            scan = user.planet.scan("A")
            if scan is None:
                message.reply("Advanced Unit Scan not found for %s:%s:%s" % (user.planet.x, user.planet.y, user.planet.z))
                return
        else:
            message.reply("Planet not set. Use !pref planet=x:y:z")
            return

        scanage = Updates.current_tick() - scan.tick
        if scanage > 12:
            reply += "Warning: Scan is %d ticks old.\n" % scanage

        self.update_comment_and_fleetcount(user, fleetcount, comment)
        user.fleets.delete()
        for uscan in scan.units:
            user.fleets.append(UserFleet(ship_id=uscan.ship_id, ship_count=uscan.amount))
        session.commit()

        ships = user.fleets.all()
        
        reply += "Updated your def info to: fleetcount %s, updated: pt%s ships: " % (user.fleetcount, user. fleetupdated)
        reply += ", ".join(map(lambda x:"%s %s" % (self.num2short(x.ship_count), x.ship.name), ships))
        reply += " and comment: %s" %(user.fleetcomment)
        message.reply(reply)
Beispiel #31
0
    def execute(self, message, user, params):

        eta, land_tick = params.groups()
        land_tick = int(land_tick)

        if eta.lower() in self.class_eta.keys():
            eta = self.class_eta[eta.lower()]
        else:
            try:
                eta = int(eta)
            except ValueError:
                message.alert("Invalid class or eta '%s'" % (eta, ))
                return

        current_tick = Updates.current_tick()

        current_time = datetime.datetime.utcnow()
        launch_tick = land_tick - eta
        launch_time = current_time + datetime.timedelta(hours=(launch_tick -
                                                               current_tick))
        prelaunch_tick = land_tick - eta + 1
        prelaunch_mod = launch_tick - current_tick

        message.reply(
            "eta %d landing pt %d (currently %d) must launch at pt %d (%s), or with prelaunch tick %d (currently %+d)"
            % (eta, land_tick, current_tick, launch_tick,
               (launch_time.strftime("%m-%d %H:55")), prelaunch_tick,
               prelaunch_mod))
Beispiel #32
0
    def bonus(self, message, user, params):

        # Check if tick is provided
        tick = int(params.group(1) or 0)

        if tick > PA.getint("numbers", "last_tick"):
            message.reply("Use your bonus during the round, not after.")
            return

        # If there is no tick provided in the command then check what the current tick is.
        if not tick:
            # Retrieve current tick
            tick = Updates.current_tick()
            if not tick:
                # Game not ticking yet.
                message.reply("Game is not ticking yet!")
                return

        resources = 10000 + tick * 4800
        roids = int(6 + tick * 0.15)
        research = 4000 + tick * 24
        construction = 2000 + tick * 18

        message.reply(
            "Upgrade Bonus calculation for tick {} | Resources: {:,} EACH | Roids: {:,} EACH | Research Points: {:,} | Construction Units: {:,}".format(
                tick, resources, roids, research, construction
            )
        )
Beispiel #33
0
    def execute(self, message, user, params):

        search = params.group(1)

        Q = session.query(FleetLog)

        if search is not None:
            ship = Ship.load(name=search)
            if ship is not None:
                Q = Q.filter(FleetLog.ship == ship)
            else:
                u = User.load(search, exact=False, access="member")
                if u is not None:
                    Q = Q.filter(FleetLog.user == u)
                else:
                    Q = Q.filter(FleetLog.id == -1)
        Q = Q.order_by(desc(FleetLog.tick))

        result = Q[:10]

        if len(result) < 1:
            message.reply("No matches found in the deflog for search '%s'" %
                          (search, ))
            return

        tick = Updates.current_tick()
        reply = ", ".join(
            map(
                lambda x: "%s gave %s %s to %s (%s)" %
                (x.user.name, self.num2short(x.ship_count), x.ship.name, x.
                 taker.name, x.tick - tick), result))
        message.reply(reply)
Beispiel #34
0
    def list(self, message, user, params):
        Q = session.query(func.count().label("count"), func.max(Request.id).label("max_id"))
        Q = Q.filter(Request.tick > Updates.current_tick() - 5)
        Q = Q.filter(Request.active == True)
        Q = Q.group_by(Request.planet_id, Request.scantype)
        Q = Q.order_by(asc("max_id"))
        SQ = Q.subquery()
        Q = session.query(Request, SQ.c.count).join((SQ, and_(Request.id == SQ.c.max_id)))

        if Q.count() < 1:
            message.reply("There are no open scan requests")
            return

        message.reply(
            " ".join(
                map(
                    lambda (request, count): Config.get("Misc", "reqlist").decode("string_escape")
                    % (
                        request.id,
                        request.target.intel.dists if request.target.intel else "0",
                        "/%s" % request.dists if request.dists > 0 else "",
                        request.scantype,
                        request.target.x,
                        request.target.y,
                        request.target.z,
                    ),
                    Q.all(),
                )
            )
        )
Beispiel #35
0
 def execute(self, message, user, params):
     
     search=params.group(1)
     
     Q = session.query(FleetLog)
     
     if search != "":
         ship = Ship.load(name=search)
         if ship is not None:
             Q = Q.filter(FleetLog.ship == ship)
         else:
             u = User.load(search, exact=False, access="member")
             if u is not None:
                 Q = Q.filter(FleetLog.user == u)
             else:
                 Q = Q.filter(FleetLog.id == -1)
     Q = Q.order_by(desc(FleetLog.tick))
     
     result = Q[:10]
     
     if len(result) < 1:
         message.reply("No matches found in the deflog for search '%s'"%(search,))
         return
     
     tick = Updates.current_tick()
     reply = ", ".join(map(lambda x:"%s gave %s %s to %s (%s)"%(x.user.name,self.num2short(x.ship_count),x.ship.name,x.taker.name,x.tick-tick),result))
     message.reply(reply)
Beispiel #36
0
 def update_comment_and_fleetcount(self,user,fleetcount,comment):
     user.fleetcount = fleetcount
     if comment != "":
         if comment in self.nulls:
             comment=""
         user.fleetcomment = comment
     user.fleetupdated = Updates.current_tick()
Beispiel #37
0
 def execute(self, request, user, sort=None):
     
     levels = [] + User.levels
     
     if sort is not None:
         levels = [("All member", levels[-1][1],),]
     
     order =  {"name"  : (asc(User.name),),
               "sponsor" : (asc(User.sponsor),),
               "access" : (desc(User.access),desc(User.carebears),asc(User.name),),
               "carebears" : (desc(User.carebears),),
               "planet" : (asc(Planet.x),asc(Planet.y),asc(Planet.z),),
               "defage" : (asc(User.fleetupdated),),
               }
     if sort not in order.keys():
         sort = "name"
     order = order.get(sort)
     
     members = []
     for level in levels:
         Q = session.query(User.name, User.alias, User.sponsor, User.access, User.carebears, Planet, User.fleetupdated,
                           User.phone, User.pubphone, User.id.in_(session.query(PhoneFriend.user_id).filter_by(friend=user)))
         Q = Q.outerjoin(User.planet)
         Q = Q.filter(User.active == True)
         Q = Q.filter(User.access >= level[1])
         Q = Q.filter(User.access < levels[levels.index(level)-1][1]) if levels.index(level) > 0 else Q
         for o in order:
             Q = Q.order_by(o)
         
         members.append((level[0], Q.all(),))
     
     return render("members.tpl", request, accesslist=members, tick=Updates.current_tick()*-1)
Beispiel #38
0
 def update_comment_and_fleetcount(self, user, fleetcount, comment):
     user.fleetcount = fleetcount
     if comment != "":
         if comment in self.nulls:
             comment = ""
         user.fleetcomment = comment
     user.fleetupdated = Updates.current_tick()
Beispiel #39
0
 def execute(self, message, user, params):
     reply = ""
     tick = Updates.current_tick()
     opts = params.group(1).split()
     for o in reversed(Config.options("Access")):
         if ("galmates" not in opts) and (Config.getint("Access", o) == 0):
             continue
         Q = session.query(User)
         Q = Q.filter(User.access == Config.getint("Access", o))
         Q = Q.order_by(asc(User.name))
         result = Q.all()
         if len(result) < 1:
             continue
         printable = map(
             lambda (u): "%s%s%s%s%s" %
             (u.name, ' (' + u.alias + ')'
              if u.alias else '', " (%d:%d:%d)" %
              (u.planet.x, u.planet.y, u.planet.z)
              if "coords" in opts and u.planet is not None else '', " (%s)"
              % ((u.fleetupdated or 0) - tick)
              if "defage" in opts else '', " (%s)" % (u.fleetupdated or 0)
              if "mydef" in opts else ''), result)
         reply += "%s:  " % (o)
         reply += ', '.join(printable)
         reply += '\n'
     message.reply(reply[:-1])
Beispiel #40
0
def base_context(request):
    context = {"name"   : Config.get("Alliance", "name"),
               "slogan" : Config.get("Alliance", "name"),
               "tick"   : Updates.current_tick(),
               "update" : Updates.load(),
               "graphs" : Config.get("Misc", "graphing") != "disabled",
               }
    if getattr(request, "user", None) is not None:
        context["user"] = request.user
        context["menu"] = menu.generate(request.user)
    if getattr(request, "session", None) is not None:
        slogan, count = Slogan.search("")
        if slogan is not None:
            context["slogan"] = str(slogan)
    if Config.has_section("FluxBB") and Config.getboolean("FluxBB", "enabled"):
        context["fluxurl"] = "<br><br><a href=\"%s\">Forum</a>" % (Config.get("FluxBB", "url"))
    return context
Beispiel #41
0
    def execute(self, request, user, message=None):
        tick = Updates.current_tick()

        Q = session.query(Attack)
        if user.access < (
                Config.getint("Access", "hc")
                if "hc" in Config.options("Access") else 1000
        ):  # Hide attacks until they are active, unless the user has access
            Q = Q.filter(
                Attack.landtick <= tick + Config.getint("Misc", "attactive"))
        Q = Q.filter(
            Attack.landtick + Attack.waves >=
            tick)  # Hide attacks one tick after the last wave has landed
        Q = Q.order_by(asc(Attack.id))
        attacks = Q.all()

        Q = session.query(Planet, Target.tick)
        Q = Q.join(Target.planet)
        Q = Q.join(Target.user)
        Q = Q.filter(Planet.active == True)
        Q = Q.filter(Target.user == user)
        Q = Q.filter(
            Target.tick >=
            tick - 12)  # We shouldn't need any bookings 12 ticks after landing
        Q = Q.order_by(asc(Target.tick), asc(Planet.x), asc(Planet.y),
                       asc(Planet.z))

        bookings = []
        scans = []
        for planet, tock in Q.all():
            bookings.append((
                planet,
                tock,
                [],
            ))
            if planet.scan("P"):
                bookings[-1][2].append(planet.scan("P"))
                scans.append(planet.scan("P"))

            if planet.scan("D"):
                bookings[-1][2].append(planet.scan("D"))
                scans.append(planet.scan("D"))

            if planet.scan("A") or planet.scan("U"):
                bookings[-1][2].append(planet.scan("A") or planet.scan("U"))
                scans.append(planet.scan("A") or planet.scan("U"))

            if tock <= tick + Config.getint("Misc", "attjgp") and planet.scan(
                    "J"):
                bookings[-1][2].append(planet.scan("J"))
                scans.append(planet.scan("J"))

        return render("attacks.tpl",
                      request,
                      message=message,
                      attacks=attacks,
                      bookings=bookings,
                      scans=scans)
Beispiel #42
0
    def execute(self, message, user, params):

        target = Planet.load(*params.group(1, 3, 5))
        if target is None:
            message.reply("No planet matching '%s:%s:%s' found" %
                          params.group(1, 3, 5))
            return
        replies = [str(target)]

        if self.user_has_planet(user):
            attacker = user.planet
            reply = "Target "

            reply += "%s:%s:%s (%s|%s) " % (target.x, target.y, target.z,
                                            self.num2short(target.value),
                                            self.num2short(target.score))
            reply += "| Attacker %s:%s:%s (%s|%s) " % (
                attacker.x, attacker.y, attacker.z,
                self.num2short(attacker.value), self.num2short(attacker.score))

            reply += "| Bravery: %.2f " % (attacker.bravery(target), )

            cap = target.maxcap(attacker)
            xp = attacker.calc_xp(target)
            reply += "| Roids: %s | XP: %s | Score: %s" % (
                cap, xp, xp * PA.getint("numbers", "xp_value"))
            replies.append(reply)

        if target.intel is not None:
            replies.append(
                ("Information stored for %s:%s:%s -" + str(target.intel) if
                 str(target.intel) else "No information stored for %s:%s:%s") %
                (
                    target.x,
                    target.y,
                    target.z,
                ))

        bookings = target.bookings.filter(
            Target.tick > Updates.current_tick()).all()
        if len(bookings) < 1:
            replies.append("No bookings matching planet %s:%s:%s" % (
                target.x,
                target.y,
                target.z,
            ))
        else:
            prev = []
            for booking in bookings:
                prev.append("(%s user:%s)" % (booking.tick, booking.user.name))
            replies.append("Status for %s:%s:%s - " % (
                target.x,
                target.y,
                target.z,
            ) + ", ".join(prev))

        message.reply("\n".join(replies))
Beispiel #43
0
    def tick(self, message, user, params):
        tick = Updates.load(params.group(1)) or Updates.current_tick()
        if isinstance(tick, Updates):  # We have that tick
            message.reply(str(tick))
        elif tick == 0:  # We don't have any ticks
            ticktime = GameSetup.getint("round_start_time") + (
                int(params.group(1)) - 1) * GameSetup.getint("tick_speed")
            tdiff = int(ticktime - time.time())
            tdelta = abs(tdiff / 86400)
            retstr = " %sd" % tdelta if tdelta else ""
            tdelta = (tdiff % 86400) / 3600
            retstr += " %sh" % tdelta if tdelta else ""
            tdelta = (tdiff % 3600) / 60
            retstr += " %sm" % tdelta if tdelta else ""
            retstr = "Tick %s %s expected to happen%s%s%s - %s" % (
                params.group(1), "is" if tdiff >= 0 else "was", " in"
                if tdiff >= 0 else "", retstr, " ago" if tdiff < 0 else "",
                datetime.utcfromtimestamp(
                    float(ticktime)).strftime("%a %d/%m %H:%M UTC"))
            message.reply(retstr)
        else:  # We have some ticks, but not that one
            diff = int(params.group(1)) - tick
            now = datetime.utcnow()
            tick_speed = GameSetup.getint("tick_speed")
            tdiff = timedelta(seconds=tick_speed * diff) - timedelta(
                minutes=now.minute % (tick_speed / 60))
            retstr = "%sd " % abs(tdiff.days) if tdiff.days else ""
            retstr += "%sh " % abs(tdiff.seconds /
                                   3600) if tdiff.seconds / 3600 else ""
            retstr += "%sm " % abs(tdiff.seconds % 3600 /
                                   60) if tdiff.seconds % 3600 / 60 else ""

            if diff == 1:
                retstr = "Next tick is %s (in %s" % (params.group(1), retstr)
            elif diff > 1:
                retstr = "Tick %s is expected to happen in %s ticks (in %s" % (
                    params.group(1), diff, retstr)
            elif diff <= 0:
                retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (
                    params.group(1), -diff, retstr)

            ticktime = now + tdiff
            retstr += " - %s)" % (ticktime.strftime("%a %d/%m %H:%M UTC"), )
            message.reply(retstr)
Beispiel #44
0
    def __init__(self, message, m):

        scanlog(asctime())
        try:
            pnick = "(%s)" % message.get_pnick()
        except:
            pnick = ""
        scanlog("Galaxy status from %s%s" % (message.get_nick(), pnick))

        target_x=m.group(1)
        target_y=m.group(2)
        target_z=m.group(3)

        owner_x=m.group(4)
        owner_y=m.group(5)
        owner_z=m.group(6)



        mission=m.group(7)
        fleetname=m.group(8)
#        race=m.group(10)
        fleetsize=m.group(11)
        eta=m.group(12)

        if mission == "A":
            mission = "Attack"
        elif mission == "D":
            mission = "Defend"
        elif mission == "R":
            mission = "Return"

        target=Planet.load(target_x,target_y,target_z)
        if target is None:
            return

        owner=Planet.load(owner_x,owner_y,owner_z)
        if owner is None:
            return

        curtick=Updates.current_tick()
        landing_tick = int(eta) + int(curtick)

        scanlog("%s:%s:%s %s:%s:%s '%s' %s %s eta %s" % (owner_x,owner_y,owner_z,target_x,target_y,target_z,fleetname,fleetsize,mission,eta))

        fleet = FleetScan(owner=owner, target=target, fleet_size=fleetsize, fleet_name=fleetname, landing_tick=landing_tick, mission=mission)
        fleet.in_cluster = owner_x == target_x
        fleet.in_galaxy = fleet.in_cluster and owner_y == target_y
        try:
            session.add(fleet)
            session.commit()
        except IntegrityError,e:
            session.rollback()
            print "Exception in galstatus: "+e.__str__()
            scanlog("Exception in galstatus: "+e.__str__())
            traceback.print_exc()
Beispiel #45
0
 def execute(self, request, user, x, y, z, h=False, hs=False, ticks=None):
     planet = Planet.load(x,y,z)
     if planet is None:
         return HttpResponseRedirect(reverse("planet_ranks"))
     
     ticks = int(ticks or 0) if (h or hs) else 12
     
     if not hs:
         sizediffvalue = PlanetHistory.rdiff * PA.getint("numbers", "roid_value")
         valuediffwsizevalue = PlanetHistory.vdiff - sizediffvalue
         resvalue = valuediffwsizevalue * PA.getint("numbers", "res_value")
         shipvalue = valuediffwsizevalue * PA.getint("numbers", "ship_value")
         xpvalue = PlanetHistory.xdiff * PA.getint("numbers", "xp_value")
         Q = session.query(PlanetHistory,
                             sizediffvalue,
                             valuediffwsizevalue,
                             resvalue, shipvalue,
                             xpvalue,
                             )
         Q = Q.filter(PlanetHistory.current == planet)
         Q = Q.order_by(desc(PlanetHistory.tick))
         history = Q[:ticks] if ticks else Q.all()
     else:
         history = None
     
     if not (h or hs):
         landings = session.query(PlanetLandings.hour, count()).filter(PlanetLandings.planet==planet).group_by(PlanetLandings.hour).all()
         landed = session.query(PlanetLandedOn.hour, count()).filter(PlanetLandedOn.planet==planet).group_by(PlanetLandedOn.hour).all()
         vdrops = session.query(PlanetValueDrops.hour, count()).filter(PlanetValueDrops.planet==planet).group_by(PlanetValueDrops.hour).all()
         idles = session.query(PlanetIdles.hour, count()).filter(PlanetIdles.planet==planet).group_by(PlanetIdles.hour).all()
         hourstats = {
                         'landings' : dict(landings), 'landingsT' : sum([c for hour,c in landings]),
                         'landed'   : dict(landed),   'landedT'   : sum([c for hour,c in landed]),
                         'vdrops'   : dict(vdrops),   'vdropsT'   : sum([c for hour,c in vdrops]),
                         'idles'    : dict(idles),    'idlesT'    : sum([c for hour,c in idles]),
                         }
     else:
         hourstats = None
     
     if not h:
         Q = session.query(PlanetHistory)
         Q = Q.filter(or_(PlanetHistory.hour == 23, PlanetHistory.tick == Updates.current_tick()))
         Q = Q.filter(PlanetHistory.current == planet)
         Q = Q.order_by(desc(PlanetHistory.tick))
         hsummary = Q.all() if hs else Q[:14]
     else:
         hsummary = None
     
     return render(["planet.tpl",["hplanet.tpl","hsplanet.tpl"][hs]][h or hs],
                     request,
                     planet = planet,
                     history = history,
                     hour = datetime.utcnow().hour, hourstats = hourstats,
                     hsummary = hsummary,
                     ticks = ticks,
                   )
Beispiel #46
0
def base_context(request):
    context = {"name": Config.get("Alliance", "name"), "slogan": Config.get("Alliance", "name")}
    if request.session is not None:
        slogan, count = Slogan.search("")
        if slogan is not None:
            context["slogan"] = str(slogan)
        context["user"] = request.session.user
        context["menu"] = menu.generate(request.session.user)
        context["tick"] = Updates.current_tick()
    return context
Beispiel #47
0
def base_context(request):
    context = {
        "name": Config.get("Alliance", "name"),
        "slogan": Config.get("Alliance", "name"),
        "tick": Updates.current_tick(),
        "update": Updates.load(),
        "graphs": Config.get("Misc", "graphing") != "disabled",
    }
    if getattr(request, "user", None) is not None:
        context["user"] = request.user
        context["menu"] = menu.generate(request.user)
    if getattr(request, "session", None) is not None:
        slogan, count = Slogan.search("")
        if slogan is not None:
            context["slogan"] = str(slogan)
    if Config.has_section("FluxBB") and Config.getboolean("FluxBB", "enabled"):
        context["fluxurl"] = "<br><br><a href=\"%s\">Forum</a>" % (Config.get(
            "FluxBB", "url"))
    return context
Beispiel #48
0
 def execute(self, request, user, x, y, h=False, hs=False, ticks=None):
     galaxy = Galaxy.load(x,y)
     if galaxy is None:
         return HttpResponseRedirect(reverse("galaxy_ranks"))
     
     ticks = int(ticks or 0) if (h or hs) else 12
     
     if not (h or hs):
         Q = session.query(Planet, Intel.nick, Alliance.name)
         Q = Q.outerjoin(Planet.intel)
         Q = Q.outerjoin(Intel.alliance)
         Q = Q.filter(Planet.active == True)
         Q = Q.filter(Planet.galaxy == galaxy)
         Q = Q.order_by(asc(Planet.z))
         planets = Q.all()
         exiles = galaxy.exiles[:10]
     else:
         planets, exiles = None, None
     
     if not hs:
         sizediffvalue = GalaxyHistory.rdiff * PA.getint("numbers", "roid_value")
         valuediffwsizevalue = GalaxyHistory.vdiff - sizediffvalue
         resvalue = valuediffwsizevalue * PA.getint("numbers", "res_value")
         shipvalue = valuediffwsizevalue * PA.getint("numbers", "ship_value")
         xpvalue = GalaxyHistory.xdiff * PA.getint("numbers", "xp_value")
         Q = session.query(GalaxyHistory,
                             sizediffvalue,
                             valuediffwsizevalue,
                             resvalue, shipvalue,
                             xpvalue,
                             )
         Q = Q.filter(GalaxyHistory.current == galaxy)
         Q = Q.order_by(desc(GalaxyHistory.tick))
         history = Q[:ticks] if ticks else Q.all()
     else:
         history = None
     
     if not h:
         Q = session.query(GalaxyHistory)
         Q = Q.filter(or_(GalaxyHistory.hour == 23, GalaxyHistory.tick == Updates.current_tick()))
         Q = Q.filter(GalaxyHistory.current == galaxy)
         Q = Q.order_by(desc(GalaxyHistory.tick))
         hsummary = Q.all() if hs else Q[:14]
     else:
         hsummary = None
     
     return render(["galaxy.tpl",["hgalaxy.tpl","hsgalaxy.tpl"][hs]][h or hs],
                     request,
                     galaxy = galaxy,
                     planets = planets,
                     exiles = exiles,
                     history = history,
                     hsummary = hsummary,
                     ticks = ticks,
                   )
Beispiel #49
0
    def new(self, message, user, params):
        tick = Updates.current_tick()
        comment = params.group(4) or ""
        when = int(params.group(1))
        waves = params.group(2) or Config.get("Misc", "attwaves")
        if when < PA.getint("numbers", "protection"):
            when += tick
        elif when <= tick:
            message.alert(
                "Can not create attacks in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return
        if when > 32767:
            when = 32767

        attack = Attack(landtick=when, comment=comment, waves=int(waves))
        session.add(attack)

        for coord in re.findall(loadable.coord, params.group(3)):
            if not coord[4]:
                galaxy = Galaxy.load(coord[0], coord[2])
                if galaxy:
                    attack.addGalaxy(galaxy)

            else:
                planet = Planet.load(coord[0], coord[2], coord[4])
                if planet:
                    attack.addPlanet(planet)

        session.commit()
        message.reply(str(attack))

        # Request scans
        if Config.has_option("Misc", "attscans"):
            scantypes = Config.get("Misc", "attscans")
        else:
            scantypes = ""

        for stype in scantypes:
            for p in attack.planets:
                scan = p.scan(stype)
                if scan and (int(tick) == scan.tick):
                    return
                else:
                    req = Request(target=p, scantype=stype, dists=0)
                    user.requests.append(req)
                    session.commit()
                    push("request", request_id=req.id, mode="request")
        if scantypes:
            message.reply("Scans requested: %s" % (scantypes))
Beispiel #50
0
 def list(self, message, user, params):
     Q = session.query(Request)
     Q = Q.filter(Request.tick > Updates.current_tick() - 5)
     Q = Q.filter(Request.active == True)
     Q = Q.order_by(asc(Request.id))
     
     if Q.count() < 1:
         message.reply("There are no open scan requests")
         return
     
     message.reply(" ".join(map(lambda request: Config.get("Misc", "reqlist").decode("string_escape") % (request.id, request.target.intel.dists if request.target.intel else "0",
             "/%s" % request.dists if request.dists > 0 else "", request.scantype, request.target.x, request.target.y, request.target.z,), Q.all())))
Beispiel #51
0
 def drop_ships(self, user, taker, ships):
     removed = {}
     tick = Updates.current_tick()
     for name in ships.split():
         ship = Ship.load(name=name)
         if ship is None:
             continue
         for fleet in user.fleets.filter_by(ship=ship):
             removed[fleet.ship.name] = fleet.ship_count
             self.delete_ships(user, taker, fleet, tick)
     session.commit()
     return removed
Beispiel #52
0
    def execute(self, message, user, params):

        p = Planet.load(*params.group(1, 3, 5))
        if p is None:
            message.alert("No planet with coords %s:%s:%s" %
                          params.group(1, 3, 5))
            return
        tick = params.group(6)

        p1 = aliased(PlanetHistory)
        p2 = aliased(PlanetHistory)
        Q = session.query(p1.tick, p1.value, p1.value - p2.value, p1.size,
                          p1.size - p2.size)
        Q = Q.filter(and_(p1.id == p2.id, p1.tick - 1 == p2.tick))
        Q = Q.filter(p1.current == p)

        if tick:
            Q = Q.filter(p1.tick == tick)
            result = Q.first()
            if result is None:
                message.reply("No data for %s:%s:%s on tick %s" %
                              (p.x, p.y, p.z, tick))
                return

            tick, value, vdiff, size, rdiff = result
            reply = "Value on pt%s for %s:%s:%s: " % (tick, p.x, p.y, p.z)
            reply += "value: %s (%s%s)" % (value, ["+", ""][vdiff < 0], vdiff)
            if rdiff != 0:
                reply += " roids: %s%s" % (["+", ""][rdiff < 0], rdiff)
            message.reply(reply)
        else:
            tick = Updates.current_tick()
            Q = Q.filter(p1.tick > (tick - 16)).order_by(asc(p1.tick))
            result = Q.all()
            if len(result) < 1:
                message.reply("No data for %s:%s:%s" % (p.x, p.y, p.z))
                return

            prev = []
            for tick, value, vdiff, size, rdiff in result:
                reply = "pt%s %s (%s%s)" % (
                    tick,
                    self.num2short(value),
                    ["+", ""][vdiff < 0],
                    self.num2short(vdiff),
                )
                if rdiff != 0:
                    reply += " roids: %s%s" % (["+", ""][rdiff < 0], rdiff)
                prev.append(reply)
            reply = "Value in the last 15 ticks on %s:%s:%s: " % (
                p.x, p.y, p.z) + ' | '.join(prev)
            message.reply(reply)
Beispiel #53
0
    def list(self, message, user, params):
        Q = session.query(Attack)
        if user.access < (
                Config.getint("Access", "hc")
                if "hc" in Config.options("Access") else 1000
        ):  # Hide attacks until they are active, unless the user has access
            Q = Q.filter(Attack.landtick <= Updates.current_tick() +
                         Config.getint("Misc", "attactive"))
        Q = Q.filter(Attack.landtick + Attack.waves >= Updates.current_tick()
                     )  # Hide attacks one tick after the last wave has landed
        Q = Q.order_by(asc(Attack.id))

        replies = []
        for attack in Q:
            replies.append("(%d LT: %d %s)" % (
                attack.id,
                attack.landtick,
                attack.comment,
            ))

        reply = "Open attacks: " + " ".join(replies)
        message.reply(reply)
Beispiel #54
0
    def execute(self, request, user, id, message=None):
        attack = Attack.load(id)
        if attack is None or not attack.active:
            return HttpResponseRedirect(reverse("attacks"))

        waves = xrange(attack.landtick, attack.landtick + Attack._waves)
        show_jgps = attack.landtick <= Updates.current_tick(
        ) + Attack._show_jgp_ticks

        group = []
        scans = []
        for planet in attack.planets:
            group.append((
                planet,
                [],
                [],
            ))
            if planet.scan("P"):
                group[-1][1].append(planet.scan("P"))
                scans.append(planet.scan("P"))

            if planet.scan("D"):
                group[-1][1].append(planet.scan("D"))
                scans.append(planet.scan("D"))

            if planet.scan("A") or planet.scan("U"):
                group[-1][1].append(planet.scan("A") or planet.scan("U"))
                scans.append(planet.scan("A") or planet.scan("U"))

            if show_jgps and planet.scan("J"):
                group[-1][1].append(planet.scan("J"))
                scans.append(planet.scan("J"))

            bookings = dict([(
                target.tick,
                target,
            ) for target in planet.bookings.filter(
                Target.tick.between(attack.landtick, attack.landtick + 4))])
            for tick in waves:
                group[-1][2].append((
                    tick,
                    bookings.get(tick) or (False if show_jgps else None),
                ))

        return render("attack.tpl",
                      request,
                      attack=attack,
                      message=message,
                      waves=waves,
                      group=group,
                      scans=scans)
Beispiel #55
0
    def execute(self, request, user, message=None):
        tick = Updates.current_tick()

        Q = session.query(Attack)
        Q = Q.filter(
            Attack.landtick >= tick - Config.getint("Misc", "attactive"))
        Q = Q.order_by(asc(Attack.id))
        attacks = Q.all()

        Q = session.query(Planet, Target.tick)
        Q = Q.join(Target.planet)
        Q = Q.join(Target.user)
        Q = Q.filter(Planet.active == True)
        Q = Q.filter(Target.user == user)
        Q = Q.filter(Target.tick >= tick - Config.getint("Misc", "attactive"))
        Q = Q.order_by(asc(Target.tick), asc(Planet.x), asc(Planet.y),
                       asc(Planet.z))

        bookings = []
        scans = []
        for planet, tock in Q.all():
            bookings.append((
                planet,
                tock,
                [],
            ))
            if planet.scan("P"):
                bookings[-1][2].append(planet.scan("P"))
                scans.append(planet.scan("P"))

            if planet.scan("D"):
                bookings[-1][2].append(planet.scan("D"))
                scans.append(planet.scan("D"))

            if planet.scan("A") or planet.scan("U"):
                bookings[-1][2].append(planet.scan("A") or planet.scan("U"))
                scans.append(planet.scan("A") or planet.scan("U"))

            if tock <= tick + Config.getint("Misc", "attjgp") and planet.scan(
                    "J"):
                bookings[-1][2].append(planet.scan("J"))
                scans.append(planet.scan("J"))

        return render("attacks.tpl",
                      request,
                      message=message,
                      attacks=attacks,
                      bookings=bookings,
                      scans=scans)
Beispiel #56
0
    def show(self, message, user, params):
        id = params.group(1)
        attack = Attack.load(id)

        if attack is None:
            message.alert("No attack exists with id %s" % (id))
            return
        if user.access < (Config.getint("Access", "hc")
                          if "hc" in Config.options("Access") else
                          1000) and attack.landtick > Updates.current_tick(
                          ) + Config.getint("Misc", "attactive"):
            message.alert("Attack %s is not open yet" % (id))
            return

        message.reply(str(attack))
Beispiel #57
0
 def list(self, message, user, params):
     Q = session.query(func.count().label('count'), func.max(Request.id).label('max_id'))
     Q = Q.filter(Request.tick > Updates.current_tick() - 5)
     Q = Q.filter(Request.active == True)
     Q = Q.group_by(Request.planet_id, Request.scantype)
     Q = Q.order_by(asc('max_id'))
     SQ = Q.subquery()
     Q = session.query(Request, SQ.c.count).join((SQ, and_(Request.id == SQ.c.max_id)))
     
     if Q.count() < 1:
         message.reply("There are no open scan requests")
         return
     
     message.reply(" ".join(map(lambda (request, count): Config.get("Misc", "reqlist").decode("string_escape") % (request.id, request.target.intel.dists if request.target.intel else "0",
                   "/%s" % request.dists if request.dists > 0 else "", request.scantype, request.target.x, request.target.y, request.target.z,), Q.all())))
Beispiel #58
0
    def execute(self, message, planet=None, galaxy=None, alliance=None):
        tick = Updates.current_tick()
        target = aliased(Planet)
        target_intel = aliased(Intel)
        owner = aliased(Planet)
        owner_intel = aliased(Intel)

        Q = session.query(Alliance.name, count())
        Q = Q.join((FleetScan.owner, owner))
        Q = Q.join((FleetScan.target, target))
        Q = Q.filter(FleetScan.mission == "Attack")
        Q = Q.outerjoin((owner.intel, owner_intel))
        Q = Q.outerjoin((owner_intel.alliance, Alliance))
        if planet:
            Q = Q.filter(FleetScan.target == planet)
        if galaxy:
            Q = Q.filter(target.galaxy == galaxy)
        if alliance:
            Q = Q.join((target.intel, target_intel))
            Q = Q.filter(target_intel.alliance == alliance)
        Q = Q.group_by(Alliance.name)
        Q = Q.order_by(desc(count()))
        result = Q.all()

        if len(result) < 1:
            reply = "No fleets found targetting"
            if planet:
                reply += " coords %s:%s:%s" % (planet.x, planet.y, planet.z)
            if galaxy:
                reply += " coords %s:%s" % (galaxy.x, galaxy.y)
            if alliance:
                reply += " alliance %s" % (alliance.name, )
            message.reply(reply)
            return

        reply = "Top attackers on"
        if planet:
            reply += " coords %s:%s:%s" % (planet.x, planet.y, planet.z)
        if galaxy:
            reply += " coords %s:%s" % (galaxy.x, galaxy.y)
        if alliance:
            reply += " alliance %s" % (alliance.name, )
        reply += " are (total: %s) " % (sum(
            [attacks for name, attacks in result]), )
        prev = []
        for name, attacks in result[:5]:
            prev.append("%s - %s" % (name or "Unknown", attacks))
        message.reply(reply + " | ".join(prev))