Skip to content

Commit

Permalink
Merge branch 'raids' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
tallypokemap authored Jul 24, 2017
2 parents a550a64 + 76a31d2 commit 59f2524
Show file tree
Hide file tree
Showing 15 changed files with 386 additions and 50 deletions.
133 changes: 127 additions & 6 deletions monocle/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
log = get_logger(__name__)

if conf.DB_ENGINE.startswith('mysql'):
from sqlalchemy.dialects.mysql import TINYINT, MEDIUMINT, BIGINT, DOUBLE
from sqlalchemy.dialects.mysql import TINYINT, MEDIUMINT, BIGINT, DOUBLE, BOOLEAN

TINY_TYPE = TINYINT(unsigned=True) # 0 to 255
MEDIUM_TYPE = MEDIUMINT(unsigned=True) # 0 to 4294967295
HUGE_TYPE = BIGINT(unsigned=True) # 0 to 18446744073709551615
FLOAT_TYPE = DOUBLE(precision=17, scale=14, asdecimal=False)
elif conf.DB_ENGINE.startswith('postgres'):
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, BOOLEAN

class NumInt(TypeDecorator):
'''Modify Numeric type for integers'''
Expand Down Expand Up @@ -191,10 +191,53 @@ def unpickle(self):
except (FileNotFoundError, TypeError, KeyError):
pass

class RaidCache:
"""Simple cache for storing raid info"""
"""Self-delete after raid ends"""
def __init__(self):
self.raids = {}
self.class_version = 2
self.unpickle()

def __len__(self):
return len(self.raids)

def add(self, raid):
self.raids[raid['external_id']] = str(raid['raid_seed']) + str(raid.get('pokemon_id', 0))
call_at(raid['raid_end'], self.remove, raid['external_id'])

def __contains__(self, raid):
try:
return self.raids[raid['external_id']] == str(raid['raid_seed']) + str(raid.get('pokemon_id', 0))
except KeyError:
return False

def remove(self, external_id):
try:
del self.raids[external_id]
except KeyError:
pass

def pickle(self):
state = self.__dict__.copy()
state['db_hash'] = spawns.db_hash
state['bounds_hash'] = hash(bounds)
dump_pickle('forts', state)

def unpickle(self):
try:
state = load_pickle('raids', raise_exception=True)
if all((state['class_version'] == self.class_version,
state['db_hash'] == spawns.db_hash,
state['bounds_hash'] == hash(bounds))):
self.__dict__.update(state)
except (FileNotFoundError, TypeError, KeyError):
pass

SIGHTING_CACHE = SightingCache()
MYSTERY_CACHE = MysteryCache()
FORT_CACHE = FortCache()
RAID_CACHE = RaidCache()

Base = declarative_base()

Expand Down Expand Up @@ -302,8 +345,10 @@ class FortSighting(Base):
fort_id = Column(Integer, ForeignKey('forts.id'))
last_modified = Column(Integer, index=True)
team = Column(TINY_TYPE)
prestige = Column(MEDIUM_TYPE)
in_battle = Column(BOOLEAN, default=False)
guard_pokemon_id = Column(TINY_TYPE)
slots_available = Column(TINY_TYPE)
time_ocuppied = Column(Integer)

__table_args__ = (
UniqueConstraint(
Expand All @@ -313,6 +358,24 @@ class FortSighting(Base):
),
)

class RaidInfo(Base):
__tablename__ = 'raid_info'

id = Column(Integer, primary_key=True)
fort_id = Column(Integer, ForeignKey('forts.id'))
if conf.DB_ENGINE.startswith('mysql'):
raid_seed = Column(BIGINT)
elif conf.DB_ENGINE.startswith('postgres'):
raid_seed = Column(HUGE_TYPE)
raid_level = Column(TINY_TYPE)
raid_spawn = Column(Integer)
raid_start = Column(Integer, index=True)
raid_end = Column(Integer, index=True)
pokemon_id = Column(TINY_TYPE)
cp = Column(Integer)
move_1 = Column(SmallInteger)
move_2 = Column(SmallInteger)


class Pokestop(Base):
__tablename__ = 'pokestops'
Expand Down Expand Up @@ -489,13 +552,54 @@ def add_fort_sighting(session, raw_fort):
obj = FortSighting(
fort=fort,
team=raw_fort['team'],
prestige=raw_fort['prestige'],
guard_pokemon_id=raw_fort['guard_pokemon_id'],
last_modified=raw_fort['last_modified'],
in_battle=raw_fort['in_battle'],
slots_available=raw_fort['slots_available'],
time_ocuppied=raw_fort['time_ocuppied']
)
session.add(obj)
FORT_CACHE.add(raw_fort)

def add_raid_info(session, raw_raid):
# Check if raid_seed exists
raid = session.query(RaidInfo) \
.filter(RaidInfo.raid_seed == raw_raid['raid_seed']) \
.first()
if raid:
if raid.pokemon_id is None and raw_raid.get('pokemon_id') is not None:
raid.pokemon_id = raw_raid['pokemon_id']
raid.cp = raw_raid['cp']
raid.move_1 = raw_raid['move_1']
raid.move_2 = raw_raid['move_2']
RAID_CACHE.add(raw_raid)
return
else:
# This raid is not in cache?
RAID_CACHE.add(raw_raid)
return

# Get fort id
fort = session.query(Fort) \
.filter(Fort.external_id == raw_raid['external_id']) \
.first()
# Fort not found in db? Ignore raid.
if fort is None:
return
raid = RaidInfo(
fort_id=fort.id,
raid_seed=raw_raid['raid_seed'],
raid_level=raw_raid['raid_level'],
raid_spawn=raw_raid['raid_spawn'],
raid_start=raw_raid['raid_start'],
raid_end=raw_raid['raid_end'],
pokemon_id=raw_raid.get('pokemon_id'),
cp=raw_raid.get('cp'),
move_1=raw_raid.get('move_1'),
move_2=raw_raid.get('move_2')
)
RAID_CACHE.add(raw_raid)
session.add(raid)

def add_pokestop(session, raw_pokestop):
pokestop_id = raw_pokestop['external_id']
Expand Down Expand Up @@ -561,7 +665,6 @@ def _get_forts_sqlite(session):
fs.fort_id,
fs.id,
fs.team,
fs.prestige,
fs.guard_pokemon_id,
fs.last_modified,
f.lat,
Expand All @@ -582,9 +685,11 @@ def _get_forts(session):
fs.fort_id,
fs.id,
fs.team,
fs.prestige,
fs.guard_pokemon_id,
fs.last_modified,
fs.in_battle,
fs.slots_available,
fs.time_ocuppied,
f.lat,
f.lon
FROM fort_sightings fs
Expand All @@ -598,6 +703,22 @@ def _get_forts(session):

get_forts = _get_forts_sqlite if DB_TYPE == 'sqlite' else _get_forts

def get_raids_info(session):
return session.execute('''
SELECT
f.id,
ri.raid_start,
ri.raid_end,
ri.pokemon_id,
ri.cp,
ri.move_1,
ri.move_2,
ri.raid_level
FROM forts f
JOIN raid_info ri ON ri.fort_id = f.id
WHERE ri.raid_start >= {}
OR ri.raid_end >= {}
'''.format(time(), time())).fetchall()

def get_session_stats(session):
query = session.query(func.min(Sighting.expire_timestamp),
Expand Down
2 changes: 2 additions & 0 deletions monocle/db_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ def run(self):
self.count += 1
elif item_type == 'fort':
db.add_fort_sighting(session, item)
elif item_type == 'raidinfo':
db.add_raid_info(session, item)
elif item_type == 'pokestop':
db.add_pokestop(session, item)
elif item_type == 'target':
Expand Down
28 changes: 28 additions & 0 deletions monocle/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,34 @@ async def notify(self, pokemon, time_of_day):
else:
return self.cleanup(encounter_id, cache_handle)

# Notify about a raid through webhook - TODO refactor notify to support raid + pokemon in one
async def notifyRaid(self, raid_info, gym):
if WEBHOOK:
whpushed = await self.webhookRaid(raid_info, gym)

# FIXME figure out wtf notify() does if whpushed goes wrong
return True

async def webhookRaid(self, raid, fort):
data = {
'type': "raid",
'message': {
"raid_seed": raid['raid_seed'],
"pokemon_id": raid.get('pokemon_id', 0),
"cp": raid.get('cp', 0),
"move_1": raid.get('move_1', 0),
"move_2": raid.get('move_2', 0),
"start": raid['raid_start'],
"end": raid['raid_end'],
"level": raid['raid_level'],
"latitude": fort['lat'],
"longitude": fort['lon']
}
}

session = SessionManager.get()
return await self.wh_send(session, data)

async def webhook(self, pokemon):
""" Send a notification via webhook
"""
Expand Down
16 changes: 16 additions & 0 deletions monocle/static/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,22 @@
padding: 0;
}

.gymmarker {
position: absolute;
left: -16px;
top: -20px;
text-align: center;
margin: 0;
padding: 0;
width: 36px;
}

.gymmarker > img {
position: relative;
width: 36px;
height: 36px;
}

#settings>.page-header{
padding-bottom: 5px;
margin: 20px 0 10px;
Expand Down
Binary file added monocle/static/img/egg-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added monocle/static/img/egg-2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added monocle/static/img/egg-3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added monocle/static/img/egg-4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added monocle/static/img/egg-5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 59f2524

Please sign in to comment.