Esempio n. 1
0
    def set_scanned_location(self, lat, lng, capture_time):
        log.debug("{RmWrapper::set_scanned_location} called")
        now = datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        cell_id = int(S2Helper.lat_lng_to_cell_id(float(lat), float(lng), 16))
        query = (
            "INSERT INTO scannedlocation (cellid, latitude, longitude, last_modified, done, band1, band2, "
            "band3, band4, band5, midpoint, width) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
            "ON DUPLICATE KEY UPDATE last_modified=VALUES(last_modified)"
        )
        # TODO: think of a better "unique, real number"
        vals = (cell_id, lat, lng, now, -1, -1, -1, -1, -1, -1, -1, -1)
        self.execute(query, vals, commit=True)

        log.debug("{RmWrapper::set_scanned_location} Done setting location...")
        return True
Esempio n. 2
0
    def submit_gyms_map_proto(self, origin, map_proto):
        log.debug("Inserting/Updating gyms sent by %s" % str(origin))
        cells = map_proto.get("cells", None)
        if cells is None:
            return False

        now = int(time.time())

        vals_forts = []
        vals_fort_sightings = []

        query_forts = (
            "INSERT IGNORE INTO forts (external_id, lat, lon, name, url, "
            "sponsor, weather_cell_id, parkid, park) "
            "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)")

        query_fort_sightings = (
            "INSERT INTO fort_sightings (fort_id, last_modified, team, guard_pokemon_id, "
            "slots_available, is_in_battle, updated) "
            "VALUES ((SELECT id FROM forts WHERE external_id = %s), %s, %s, %s, %s, %s, %s)"
            "ON DUPLICATE KEY UPDATE  last_modified=VALUES(last_modified), team=VALUES(team),"
            "guard_pokemon_id=VALUES(guard_pokemon_id),slots_available=VALUES(slots_available),"
            "is_in_battle=VALUES(is_in_battle), updated=VALUES(updated)")

        for cell in cells:
            for gym in cell['forts']:
                if gym['type'] == 0:
                    gym_id = gym['id']
                    guardmon = gym['gym_details']['guard_pokemon']
                    lat = gym['latitude']
                    lon = gym['longitude']
                    image_uri = gym['image_url']
                    s2_cell_id = S2Helper.lat_lng_to_cell_id(lat, lon)
                    team = gym['gym_details']['owned_by_team']
                    slots = gym['gym_details']['slots_available']
                    is_in_battle = gym['gym_details'].get(
                        'is_in_battle', False)
                    last_modified = gym['last_modified_timestamp_ms'] / 1000
                    if is_in_battle:
                        is_in_battle = 1
                    else:
                        is_in_battle = 0

                    raidendSec = 0
                    if gym['gym_details']['has_raid']:
                        raidendSec = int(
                            gym['gym_details']['raid_info']['raid_end'] / 1000)

                    self.webhook_helper.send_gym_webhook(
                        gym_id, raidendSec, 'unknown', team, slots, guardmon,
                        lat, lon, last_modified)

                    vals_forts.append((gym_id, lat, lon, None, image_uri, None,
                                       s2_cell_id, None, None))

                    vals_fort_sightings.append(
                        (gym_id, last_modified, team, guardmon, slots,
                         is_in_battle, now))

        self.executemany(query_forts, vals_forts, commit=True)
        self.executemany(query_fort_sightings,
                         vals_fort_sightings,
                         commit=True)
        return True
Esempio n. 3
0
    def submit_mons_map_proto(self, origin, map_proto, mon_ids_iv):
        cells = map_proto.get("cells", None)
        if cells is None:
            return False
        query_mons_insert = (
            "INSERT IGNORE INTO sightings (pokemon_id, spawn_id, expire_timestamp, encounter_id, "
            "lat, lon, updated, gender, form, weather_boosted_condition, costume, weather_cell_id) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")

        mon_vals_insert = []

        for cell in cells:
            for wild_mon in cell['wild_pokemon']:
                spawnid = int(str(wild_mon['spawnpoint_id']), 16)
                lat = wild_mon['latitude']
                lon = wild_mon['longitude']
                now = int(time.time())
                encounter_id = wild_mon['encounter_id']
                if encounter_id < 0:
                    encounter_id = encounter_id + 2**64

                s2_weather_cell_id = S2Helper.lat_lng_to_cell_id(lat,
                                                                 lon,
                                                                 level=10)

                despawn_time = datetime.now() + timedelta(seconds=300)
                despawn_time_unix = int(time.mktime(despawn_time.timetuple()))

                init = True

                getdetspawntime = self.get_detected_endtime(str(spawnid))

                if getdetspawntime:
                    despawn_time = self._gen_endtime(getdetspawntime)
                    despawn_time_unix = despawn_time
                    init = False

                if init:
                    log.info(
                        "{0}: adding mon with id #{1} at {2}, {3}. Despawning at {4} (init)"
                        .format(str(origin), wild_mon['pokemon_data']['id'],
                                lat, lon, despawn_time))
                else:
                    log.info(
                        "{0}: adding mon with id #{1} at {2}, {3}. Despawning at {4} (non-init)"
                        .format(str(origin), wild_mon['pokemon_data']['id'],
                                lat, lon, despawn_time))

                mon_id = wild_mon['pokemon_data']['id']

                if mon_ids_iv is not None and mon_id not in mon_ids_iv or mon_ids_iv is None:
                    self.webhook_helper.send_pokemon_webhook(
                        encounter_id,
                        mon_id,
                        time.time(),
                        spawnid,
                        lat,
                        lon,
                        despawn_time_unix,
                        form=wild_mon['pokemon_data']['display']['form_value'],
                        gender=wild_mon['pokemon_data']['display']
                        ['gender_value'],
                        boosted_weather=wild_mon['pokemon_data']['display']
                        ['weather_boosted_value'])

                mon_vals_insert.append(
                    (mon_id, spawnid, despawn_time_unix, encounter_id, lat,
                     lon, now,
                     wild_mon['pokemon_data']['display']['gender_value'],
                     wild_mon['pokemon_data']['display']['form_value'],
                     wild_mon['pokemon_data']['display']
                     ['weather_boosted_value'],
                     wild_mon['pokemon_data']['display']['costume_value'],
                     s2_weather_cell_id))

        self.executemany(query_mons_insert, mon_vals_insert, commit=True)
        return True
Esempio n. 4
0
    def submit_mon_iv(self, origin, timestamp, encounter_proto):
        log.debug("Updating IV sent by %s" % str(origin))
        wild_pokemon = encounter_proto.get("wild_pokemon", None)
        if wild_pokemon is None:
            return

        query_insert = (
            "INSERT sightings (pokemon_id, spawn_id, expire_timestamp, encounter_id, "
            "lat, lon, updated, gender, form, costume, weather_boosted_condition, weather_cell_id, "
            "atk_iv, def_iv, sta_iv, move_1, move_2, cp, level, weight) "
            "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
            "ON DUPLICATE KEY UPDATE updated=VALUES(updated), atk_iv=VALUES(atk_iv), def_iv=VALUES(def_iv), "
            "sta_iv=VALUES(sta_iv), move_1=VALUES(move_1), move_2=VALUES(move_2), cp=VALUES(cp), "
            "level=VALUES(level), weight=VALUES(weight), costume=VALUES(costume)"
        )

        encounter_id = wild_pokemon['encounter_id']
        if encounter_id < 0:
            encounter_id = encounter_id + 2**64

        latitude = wild_pokemon.get("latitude")
        longitude = wild_pokemon.get("longitude")
        pokemon_data = wild_pokemon.get("pokemon_data")

        if pokemon_data.get("cp_multiplier") < 0.734:
            pokemon_level = (58.35178527 * pokemon_data.get("cp_multiplier") *
                             pokemon_data.get("cp_multiplier") -
                             2.838007664 * pokemon_data.get("cp_multiplier") +
                             0.8539209906)
        else:
            pokemon_level = 171.0112688 * pokemon_data.get(
                "cp_multiplier") - 95.20425243

            pokemon_level = round(pokemon_level) * 2 / 2

        pokemon_display = pokemon_data.get("display")
        if pokemon_display is None:
            pokemon_display = {}

        despawn_time = datetime.now() + timedelta(seconds=300)
        despawn_time_unix = int(time.mktime(despawn_time.timetuple()))
        despawn_time = datetime.utcfromtimestamp(
            time.mktime(
                despawn_time.timetuple())).strftime('%Y-%m-%d %H:%M:%S')
        init = True
        getdetspawntime = self.get_detected_endtime(
            int(str(wild_pokemon["spawnpoint_id"]), 16))

        if getdetspawntime:
            despawn_time_unix = self._gen_endtime(getdetspawntime)
            despawn_time = datetime.utcfromtimestamp(
                despawn_time_unix).strftime('%Y-%m-%d %H:%M:%S')
            init = False

        if init:
            log.info(
                "{0}: adding IV mon #{1} at {2}, {3}. Despawning at {4} (init)"
                .format(str(origin), pokemon_data["id"], latitude, longitude,
                        despawn_time))
        else:
            log.info(
                "{0}: adding IV mon #{1} at {2}, {3}. Despawning at {4} (non-init)"
                .format(str(origin), pokemon_data["id"], latitude, longitude,
                        despawn_time))

        s2_weather_cell_id = S2Helper.lat_lng_to_cell_id(latitude,
                                                         longitude,
                                                         level=10)
        vals = (
            pokemon_data["id"],
            int(wild_pokemon.get("spawnpoint_id"), 16),
            despawn_time_unix,
            encounter_id,
            latitude,
            longitude,
            timestamp,
            pokemon_display.get("gender_value", None),
            pokemon_display.get("form_value", None),
            pokemon_display.get("costume_value", None),
            pokemon_display.get("weather_boosted_value", None),
            s2_weather_cell_id,
            pokemon_data.get("individual_attack"),
            pokemon_data.get("individual_defense"),
            pokemon_data.get("individual_stamina"),
            pokemon_data.get("move_1"),
            pokemon_data.get("move_2"),
            pokemon_data.get("cp"),
            pokemon_level,
            pokemon_data.get("weight"),
        )
        self.execute(query_insert, vals, commit=True)

        self.webhook_helper.send_pokemon_webhook(
            encounter_id=encounter_id,
            pokemon_id=pokemon_data.get("id"),
            last_modified_time=timestamp,
            spawnpoint_id=int(wild_pokemon.get("spawnpoint_id"), 16),
            lat=latitude,
            lon=longitude,
            despawn_time_unix=despawn_time_unix,
            pokemon_level=pokemon_level,
            cp_multiplier=pokemon_data.get("cp_multiplier"),
            form=pokemon_display.get("form_value", None),
            cp=pokemon_data.get("cp"),
            individual_attack=pokemon_data.get("individual_attack"),
            individual_defense=pokemon_data.get("individual_defense"),
            individual_stamina=pokemon_data.get("individual_stamina"),
            move_1=pokemon_data.get("move_1"),
            move_2=pokemon_data.get("move_2"),
            height=pokemon_data.get("height"),
            weight=pokemon_data.get("weight"),
            gender=pokemon_display.get("gender_value", None),
            boosted_weather=pokemon_display.get("weather_boosted_value", None))
Esempio n. 5
0
    def _main_work_thread(self):
        current_thread().name = self.id
        log.debug("Sub called")
        # first check if pogo is running etc etc
        self._workMutex.acquire()
        try:
            self._initRoutine()
        except WebsocketWorkerRemovedException:
            log.error("Timeout during init of worker %s" % str(self.id))
            self._stop_worker_event.set()
            self._workMutex.release()
            return
        self._workMutex.release()
        # loop = asyncio.get_event_loop()
        # TODO:loop.create_task(self._speed_weather_check_thread())

        speedWeatherCheckThread = Thread(name='speedWeatherCheckThread%s' % self.id, target=self._speed_weather_check_thread)
        speedWeatherCheckThread.daemon = False
        speedWeatherCheckThread.start()

        currentLocation = self._last_known_state.get("last_location", None)
        if currentLocation is None:
            currentLocation = Location(0.0, 0.0)
        lastLocation = None
        while not self._stop_worker_event.isSet():
            while MadGlobals.sleep and self._route_manager_nighttime is None:
                time.sleep(1)
            __time = time.time()
            log.debug("Worker: acquiring lock for restart check")
            self._workMutex.acquire()
            log.debug("Worker: acquired lock")
            # Restart pogo every now and then...
            if self._devicesettings.get("restart_pogo", 80) > 0:
                # log.debug("main: Current time - lastPogoRestart: %s" % str(curTime - lastPogoRestart))
                # if curTime - lastPogoRestart >= (args.restart_pogo * 60):
                self._locationCount += 1
                if self._locationCount > self._devicesettings.get("restart_pogo", 80):
                    log.error("scanned " + str(self._devicesettings.get("restart_pogo", 80)) + " locations, restarting pogo")
                    self._restartPogo()
                    self._locationCount = 0
            self._workMutex.release()
            log.debug("Worker: lock released")

            # TODO: consider adding runWarningThreadEvent.set()
            lastLocation = currentLocation
            self._last_known_state["last_location"] = lastLocation
            if MadGlobals.sleep:
                currentLocation = self._route_manager_nighttime.getNextLocation()
                settings = self._route_manager_nighttime.settings
            else:
                currentLocation = self._route_manager_daytime.getNextLocation()
                settings = self._route_manager_daytime.settings

            # TODO: set position... needs to be adjust for multidevice
            
            posfile = open(self.id+'.position', "w")
            posfile.write(str(currentLocation.lat)+", "+str(currentLocation.lng))
            posfile.close()

            log.debug("main: next stop: %s" % (str(currentLocation)))
            log.debug('main: LastLat: %s, LastLng: %s, CurLat: %s, CurLng: %s' %
                      (lastLocation.lat, lastLocation.lng,
                       currentLocation.lat, currentLocation.lng))
            # get the distance from our current position (last) to the next gym (cur)
            distance = getDistanceOfTwoPointsInMeters(float(lastLocation.lat), float(lastLocation.lng),
                                                      float(currentLocation.lat), float(currentLocation.lng))
            log.info('main: Moving %s meters to the next position' % distance)
            delayUsed = 0
            if MadGlobals.sleep:
                speed = self._route_manager_nighttime.settings.get("speed", 0)
            else:
                speed = self._route_manager_daytime.settings.get("speed", 0)
            if (speed == 0 or
                    (settings["max_distance"] and 0 < settings["max_distance"] < distance)
                    or (lastLocation.lat == 0.0 and lastLocation.lng == 0.0)):
                log.info("main: Teleporting...")
                self._communicator.setLocation(currentLocation.lat, currentLocation.lng, 0)
                delayUsed = self._devicesettings.get("post_teleport_delay",7)
                # Test for cooldown / teleported distance TODO: check this block...
                if self._devicesettings.get("cool_down_sleep",False):
                    if distance > 2500:
                        delayUsed = 30
                    elif distance > 5000:
                        delayUsed = 45
                    elif distance > 10000:
                        delayUsed = 60
                    log.info("Need more sleep after Teleport: %s seconds!" % str(delayUsed))

                if 0 < self._devicesettings.get("walk_after_teleport_distance",0) < distance:
                    toWalk = getDistanceOfTwoPointsInMeters(float(currentLocation.lat), float(currentLocation.lng),
                                                            float(currentLocation.lat) + 0.0001,
                                                            float(currentLocation.lng) + 0.0001)
                    log.info("Walking a bit: %s" % str(toWalk))
                    time.sleep(0.3)
                    self._communicator.walkFromTo(currentLocation.lat, currentLocation.lng,
                                                   currentLocation.lat + 0.0001, currentLocation.lng + 0.0001, 11)
                    log.debug("Walking back")
                    time.sleep(0.3)
                    self._communicator.walkFromTo(currentLocation.lat + 0.0001, currentLocation.lng + 0.0001,
                                                   currentLocation.lat, currentLocation.lng, 11)
                    log.debug("Done walking")
            else:
                log.info("main: Walking...")
                self._communicator.walkFromTo(lastLocation.lat, lastLocation.lng,
                                              currentLocation.lat, currentLocation.lng,
                                              speed)
                delayUsed = self._devicesettings.get("post_walk_delay",7)
            log.info("Sleeping %s" % str(delayUsed))
            time.sleep(delayUsed)

            log.debug("main: Acquiring lock")

            while MadGlobals.sleep: # or not runWarningThreadEvent.isSet():
                time.sleep(0.1)
            log.debug("Worker: acquiring lock")
            self._workMutex.acquire()
            log.debug("main: Lock acquired")
            if not self._takeScreenshot():
                self._workMutex.release()
                log.debug("Worker: Lock released")
                continue
            log.debug("Worker: Got screenshot")
            curTime = time.time()
            if self._applicationArgs.last_scanned:
                log.info('main: Set new scannedlocation in Database')
                self._db_wrapper.set_scanned_location(str(currentLocation.lat), str(currentLocation.lng), str(curTime))
            log.info("main: Checking raidcount and copying raidscreen if raids present")
            countOfRaids = self._pogoWindowManager.readRaidCircles(os.path.join(
                self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)), self.id)
            if countOfRaids == -1:
                log.debug("Worker: Count present but no raid shown")
                log.warning("main: Count present but no raid shown, reopening raidTab")
                self._reopenRaidTab()
                # tabOutAndInPogo()
                log.debug("Done reopening raidtab")
                if not self._takeScreenshot():
                    self._workMutex.release()
                    log.debug("Worker: Lock released")
                    continue
                countOfRaids = self._pogoWindowManager.readRaidCircles(os.path.join(
                    self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)), self.id)
            #    elif countOfRaids == 0:
            #        emptycount += 1
            #        if emptycount > 30:
            #            emptycount = 0
            #            log.error("Had 30 empty scans, restarting pogo")
            #            restartPogo()

            # not an elif since we may have gotten a new screenshot..
            # detectin weather
            if self._applicationArgs.weather:
                log.debug("Worker: Checking weather...")
                weather = checkWeather(os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)))
                if weather[0]:
                    log.debug('Submit Weather')
                    cell_id = S2Helper.lat_lng_to_cell_id(currentLocation.lat, currentLocation.lng)
                    self._db_wrapper.update_insert_weather(cell_id, weather[1], curTime)
                else:
                    log.error('Weather could not detected')

            if countOfRaids > 0:
                log.debug("Worker: Count of raids >0")
                log.debug("main: New und old Screenshoot are different - starting OCR")
                log.debug("main: countOfRaids: %s" % str(countOfRaids))
                curTime = time.time()
                copyFileName = self._applicationArgs.raidscreen_path + '/raidscreen_' + str(curTime) \
                               + "_" + str(currentLocation.lat) + "_" + str(currentLocation.lng) + "_" \
                               + str(countOfRaids) + '.png'
                log.debug('Copying file: ' + copyFileName)
                log.debug("Worker: Copying file to %s" % str(copyFileName))
                copyfile(os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)), copyFileName)
                os.remove(os.path.join(self._applicationArgs.temp_path, 'screenshot%s.png' % str(self.id)))

            log.debug("main: Releasing lock")
            self._workMutex.release()
            log.debug("Worker: Lock released")
Esempio n. 6
0
    def _post_move_location_routine(self, timestamp):
        # check if the speed_weather_check_thread signalled an abort by setting the stop_worker_event
        if self._stop_worker_event.is_set():
            raise InternalStopWorkerException
        logger.debug("Main: acquiring lock")
        self._work_mutex.acquire()
        logger.debug("main: Lock acquired")
        # TODO: takeScreenshot can throw, should we care about releasing locks or just cleanup everything else?
        if not self._takeScreenshot():
            self._work_mutex.release()
            logger.debug(
                "Worker: couldn't take screenshot before radscreen check, lock released"
            )
            return

        logger.debug("Worker: Got screenshot")
        # curTime = time.time()
        logger.info(
            "main: Checking raidcount and copying raidscreen if raids present")
        count_of_raids = self._pogoWindowManager.readRaidCircles(
            self.get_screenshot_path(), self._id, self._communicator)
        if count_of_raids == -1:
            logger.debug("Worker: Count present but no raid shown")
            logger.warning(
                "main: Count present but no raid shown, reopening raidTab")
            self._reopenRaidTab()
            logger.debug("Done reopening raidtab")
            if not self._takeScreenshot():
                self._work_mutex.release()
                logger.debug(
                    "Worker: couldn't take screenshot after opening raidtab, lock released"
                )
                return
            count_of_raids = self._pogoWindowManager.readRaidCircles(
                self.get_screenshot_path(), self._id, self._communicator)
        #    elif countOfRaids == 0:
        #        emptycount += 1
        #        if emptycount > 30:
        #            emptycount = 0
        #            logger.error("Had 30 empty scans, restarting pogo")
        #            restartPogo()

        # not an elif since we may have gotten a new screenshot..
        # detectin weather
        if self._applicationArgs.weather:
            logger.debug("Worker: Checking weather...")
            weather = checkWeather(self.get_screenshot_path())
            if weather[0]:
                logger.debug('Submit Weather')
                cell_id = S2Helper.lat_lng_to_cell_id(
                    self.current_location.lat, self.current_location.lng)
                self._db_wrapper.update_insert_weather(cell_id, weather[1],
                                                       timestamp)
            else:
                logger.error('Weather could not detected')

        if count_of_raids > 0:
            logger.debug("Worker: Count of raids >0")
            logger.debug(
                "main: New und old Screenshoot are different - starting OCR")
            logger.debug("main: countOfRaids: {}", str(count_of_raids))
            timestamp = time.time()
            copyFileName = self._applicationArgs.raidscreen_path + '/raidscreen_' + str(timestamp) \
                + "_" + str(self.current_location.lat) + "_" + str(self.current_location.lng) + "_" \
                + str(count_of_raids) + '.png'
            logger.debug('Copying file: ' + copyFileName)
            logger.debug("Worker: Copying file to {}", str(copyFileName))
            copyfile(self.get_screenshot_path(), copyFileName)
            os.remove(self.get_screenshot_path())

        logger.debug("main: Releasing lock")
        self._work_mutex.release()
        logger.debug("Worker: Lock released")
Esempio n. 7
0
    def submit_gyms_map_proto(self, origin, map_proto):
        log.debug("Inserting/Updating gyms sent by %s" % str(origin))
        cells = map_proto.get("cells", None)
        if cells is None:
            return False

        now = int(time.time())

        vals_forts = []
        vals_fort_sightings_insert = []
        vals_fort_sightings_update = []

        query_forts = (
            "INSERT IGNORE INTO forts (external_id, lat, lon, name, url, "
            "sponsor, weather_cell_id, parkid, park) "
            "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)")

        query_fort_sightings_insert = (
            "INSERT INTO fort_sightings (fort_id, last_modified, team, guard_pokemon_id, "
            "slots_available, is_in_battle, updated) "
            "VALUES ((SELECT id FROM forts WHERE external_id = %s), %s, %s, %s, %s, %s, %s)"
        )

        query_fort_sightings_update = (
            "UPDATE fort_sightings SET team = %s, guard_pokemon_id = %s, "
            "slots_available = %s, updated = %s, last_modified = %s, "
            "is_in_battle=%s "
            "WHERE fort_id=(SELECT id FROM forts WHERE external_id=%s)")

        for cell in cells:
            for gym in cell['forts']:
                if gym['type'] == 0:
                    gym_id = gym['id']
                    guardmon = gym['gym_details']['guard_pokemon']
                    lat = gym['latitude']
                    lon = gym['longitude']
                    image_uri = gym['image_url']
                    s2_cell_id = S2Helper.lat_lng_to_cell_id(lat, lon)
                    team = gym['gym_details']['owned_by_team']
                    slots = gym['gym_details']['slots_available']
                    is_in_battle = gym['gym_details'].get(
                        'is_in_battle', False)
                    last_modified = gym['last_modified_timestamp_ms'] / 1000
                    if is_in_battle:
                        is_in_battle = 1
                    else:
                        is_in_battle = 0

                    raidendSec = 0
                    if gym['gym_details']['has_raid']:
                        raidendSec = int(
                            gym['gym_details']['raid_info']['raid_end'] / 1000)

                    self.webhook_helper.send_gym_webhook(
                        gym_id, raidendSec, 'unknown', team, slots, guardmon,
                        lat, lon, last_modified)

                    vals_forts.append((gym_id, lat, lon, None, image_uri, None,
                                       s2_cell_id, None, None))

                    query_get_count = "SELECT count(*) from fort_sightings where fort_id=(SELECT id from forts where " \
                                      "external_id = %s)"
                    vals_get_count = (gym_id, )
                    res = self.execute(query_get_count, vals_get_count)

                    fort_sightings_exists = res[0]
                    fort_sightings_exists = ",".join(
                        map(str, fort_sightings_exists))

                    if int(fort_sightings_exists) == 0:
                        vals_fort_sightings_insert.append(
                            (gym_id, last_modified, team, guardmon, slots,
                             is_in_battle, now))
                    else:
                        vals_fort_sightings_update.append(
                            (team, guardmon, slots, now, last_modified,
                             is_in_battle, gym_id))
        self.executemany(query_forts, vals_forts, commit=True)
        self.executemany(query_fort_sightings_insert,
                         vals_fort_sightings_insert,
                         commit=True)
        self.executemany(query_fort_sightings_update,
                         vals_fort_sightings_update,
                         commit=True)
        return True
Esempio n. 8
0
    def submit_mons_map_proto(self, map_proto):
        cells = map_proto.get("cells", None)
        if cells is None:
            return False
        query_mons = (
            "INSERT IGNORE INTO sightings (pokemon_id, spawn_id, expire_timestamp, encounter_id, "
            "lat, lon, atk_iv, def_iv, sta_iv, move_1, move_2, gender, form, cp, level, updated, "
            "weather_boosted_condition, weather_cell_id, weight) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        )

        mon_vals = []
        for cell in cells:
            for wild_mon in cell['wild_pokemon']:
                spawnid = int(str(wild_mon['spawnpoint_id']), 16)
                lat = wild_mon['latitude']
                lon = wild_mon['longitude']
                s2_weather_cell_id = S2Helper.lat_lng_to_cell_id(lat, lon, level=10)

                despawn_time = datetime.now() + timedelta(seconds=300)
                despawn_time_unix = int(time.mktime(despawn_time.timetuple()))
                now = int(time.time())
                init = True

                getdetspawntime = self.get_detected_endtime(str(spawnid))

                if getdetspawntime:
                    despawn_time = self._gen_endtime(getdetspawntime)
                    despawn_time_unix = despawn_time
                    init = False

                if init:
                    log.info("Adding mon with id #{0} at {1}, {2}. Despawning at {3} (init)"
                             .format(wild_mon['pokemon_data']['id'], lat, lon, despawn_time))
                else:
                    log.info("Adding mon with id #{0} at {1}, {2}. Despawning at {3} (non-init)"
                             .format(wild_mon['pokemon_data']['id'], lat, lon, despawn_time))

                mon_id = wild_mon['pokemon_data']['id']

                self.webhook_helper.submit_pokemon_webhook(
                    wild_mon['encounter_id'], mon_id, time.time(),
                    spawnid, lat, lon, despawn_time_unix
                )

                mon_vals.append(
                    (
                        mon_id,
                        spawnid,
                        despawn_time_unix,
                        abs(wild_mon['encounter_id']),
                        lat, lon,
                        None, None, None, None, None,  # IVs and moves
                        wild_mon['pokemon_data']['display']['gender_value'],
                        wild_mon['pokemon_data']['display']['form_value'],
                        None, None,  # CP and level
                        now,
                        wild_mon['pokemon_data']['display']['weather_boosted_value'],
                        s2_weather_cell_id,
                        None  # weight
                    )
                )

        self.executemany(query_mons, mon_vals, commit=True)
        return True