Esempio n. 1
0
 def main(self, service, api_endpoint, access_token, profile_response):
     session = db.Session()
     self.step = 0
     self.seen = 0
     for i, point in enumerate(self.points):
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         add_to_db = []
         process_step(
             service,
             api_endpoint,
             access_token,
             profile_response,
             add_to_db=add_to_db,
             lat=point[0],
             lon=point[1],
         )
         for spawn_id in add_to_db:
             pokemon = pokemons[spawn_id]
             db.add_sighting(session, spawn_id, pokemon)
             self.seen += 1
         logger.info('Point processed, %d Pokemons seen!', len(add_to_db))
         session.commit()
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen:
             self.error_code = None
         self.step += 1
     session.close()
     if self.seen == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 2
0
 def main(self, service, api_endpoint, access_token, profile_response):
     session = db.Session()
     self.seen = 0
     for i, point in enumerate(self.points):
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         add_to_db = []
         process_step(
             service,
             api_endpoint,
             access_token,
             profile_response,
             add_to_db=add_to_db,
             lat=point[0],
             lon=point[1],
         )
         for spawn_id in add_to_db:
             pokemon = pokemons[spawn_id]
             db.add_sighting(session, spawn_id, pokemon)
             self.seen += 1
         logger.info('Point processed, %d Pokemons seen!', len(add_to_db))
         session.commit()
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen:
             self.error_code = None
         self.step += 1
     session.close()
     if self.seen == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 3
0
 def run(self):
     session = db.Session()
     while self.running or self.queue:
         if self._clean_cache:
             db.SIGHTING_CACHE.clean_expired()
             self._clean_cache = False
         try:
             item = self.queue.popleft()
         except IndexError:
             self.logger.debug('No items - sleeping')
             time.sleep(0.2)
         else:
             try:
                 if item['type'] == 'pokemon':
                     db.add_sighting(session, item)
                     session.commit()
                     self.count += 1
                 elif item['type'] == 'longspawn':
                     db.add_longspawn(session, item)
                 elif item['type'] == 'fort':
                     db.add_fort_sighting(session, item)
                     # No need to commit here - db takes care of it
                 self.logger.debug('Item saved to db')
             except IntegrityError:
                 session.rollback()
                 self.logger.info(
                     'Tried and failed to add a duplicate to DB.')
             except Exception:
                 session.rollback()
                 self.logger.exception('A wild exception appeared!')
                 self.logger.info('Skipping the item.')
     session.close()
Esempio n. 4
0
    def main(self, service, api_endpoint, access_token, profile_response):
        origin_lat, origin_lon = utils.get_start_coords(self.worker_no)

        pos = 1
        x = 0
        y = 0
        dx = 0
        dy = -1
        session = db.Session()
        self.seen = 0
        for step in range(self.steplimit2):
            add_to_db = []
            self.step = step + 1
            # Scan location math
            if (
                -self.steplimit2 / 2 < x <= self.steplimit2 / 2 and
                -self.steplimit2 / 2 < y <= self.steplimit2 / 2
            ):
                lat = x * 0.0025 + origin_lat
                lon = y * 0.0025 + origin_lon
            if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
                (dx, dy) = (-dy, dx)

            (x, y) = (x + dx, y + dy)

            process_step(
                service,
                api_endpoint,
                access_token,
                profile_response,
                add_to_db=add_to_db,
                lat=lat,
                lon=lon,
            )

            for spawn_id in add_to_db:
                pokemon = pokemons[spawn_id]
                db.add_sighting(session, spawn_id, pokemon)
                self.seen += 1
            session.commit()
            add_to_db = []
            logger.info(
                'Completed: %s%%',
                ((step + 1) + pos * .25 - .25) / (self.steplimit2) * 100
            )
            # Clear error code and let know that there are Pokemon
            if self.error_code and self.seen:
                self.error_code = None
        session.close()
        if self.seen == 0:
            self.error_code = 'NO POKEMON'
        set_location_coords(origin_lat, origin_lon, 0)
Esempio n. 5
0
    def run(self):
        session = db.Session()

        while self.running or not self.queue.empty():
            if self._clean_cache:
                try:
                    db.SIGHTING_CACHE.clean_expired()
                except Exception:
                    self.logger.exception('Failed to clean sightings cache.')
                else:
                    self._clean_cache = False
                try:
                    db.MYSTERY_CACHE.clean_expired(session)
                except Exception:
                    session.rollback()
                    self.logger.exception('Failed to clean mystery cache.')
            try:
                item = self.queue.get()

                if item['type'] == 'pokemon':
                    if item['valid']:
                        db.add_sighting(session, item)
                        if item['valid'] == True:
                            db.add_spawnpoint(session, item, self.spawns)
                    else:
                        db.add_mystery(session, item, self.spawns)
                    self.count += 1
                elif item['type'] == 'fort':
                    db.add_fort_sighting(session, item)
                elif item['type'] == 'pokestop':
                    db.add_pokestop(session, item)
                elif item['type'] == 'kill':
                    break
                self.logger.debug('Item saved to db')
                if self._commit:
                    session.commit()
                    self._commit = False
            except DBAPIError as e:
                session.rollback()
                self.logger.exception('A wild DB exception appeared!')
            except Exception:
                session.rollback()
                self.logger.exception('A wild exception appeared!')

        try:
            db.MYSTERY_CACHE.clean_expired(session)
            session.commit()
        except DBAPIError:
            session.rollback()
            self.logger.exception('A wild DB exception appeared!')
        session.close()
Esempio n. 6
0
def main(worker_no, service, api_endpoint, access_token, profile_response):
    origin_lat, origin_lon = utils.get_start_coords(worker_no)

    args = get_args()

    if args.debug:
        global DEBUG
        DEBUG = True
        print '[!] DEBUG mode on'

    steplimit = int(args.step_limit)

    pos = 1
    x = 0
    y = 0
    dx = 0
    dy = -1
    steplimit2 = steplimit**2
    session = db.Session()
    for step in range(steplimit2):
        add_to_db = []
        #starting at 0 index
        debug('looping: step {} of {}'.format((step+1), steplimit**2))
        # Scan location math
        if -steplimit2 / 2 < x <= steplimit2 / 2 and -steplimit2 / 2 < y <= steplimit2 / 2:
            lat = x * 0.0025 + origin_lat
            lon = y * 0.0025 + origin_lon
        if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
            (dx, dy) = (-dy, dx)

        (x, y) = (x + dx, y + dy)

        process_step(
            service,
            api_endpoint,
            access_token,
            profile_response,
            add_to_db=add_to_db,
            lat=lat,
            lon=lon,
        )

        for spawn_id in add_to_db:
            pokemon = pokemons[spawn_id]
            db.add_sighting(session, spawn_id, pokemon)
        session.commit()
        add_to_db = []
        print('Completed: ' + str(((step+1) + pos * .25 - .25) / (steplimit2) * 100) + '%')
    session.close()
    set_location_coords(origin_lat, origin_lon, 0)
Esempio n. 7
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids
         )
         if response_dict is False:
             raise CannotProcessStep
         now = time.time()
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones will be just put after
                     # time_till_hidden is below 15 min
                     if pokemon['time_till_hidden_ms'] < 0:
                         continue
                     pokemons.append(self.normalize_pokemon(pokemon, now))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         logger.info('Point processed, %d Pokemons seen!', len(pokemons))
         session.commit()
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(
             random.uniform(config.SCAN_DELAY, config.SCAN_DELAY + 2)
         )
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 8
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids)
         if response_dict is False:
             raise CannotProcessStep
         now = time.time()
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones will be just put after
                     # time_till_hidden is below 15 min
                     if pokemon['time_till_hidden_ms'] < 0:
                         continue
                     pokemons.append(self.normalize_pokemon(pokemon, now))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         logger.info('Point processed, %d Pokemons seen!', len(pokemons))
         session.commit()
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(random.uniform(5, 7))
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 9
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids)
         if not isinstance(response_dict, dict):
             logger.warning('Response: %s', response_dict)
             raise MalformedResponse
         if response_dict['status_code'] == 3:
             logger.warning('Account banned')
             raise BannedAccount
         responses = response_dict.get('responses')
         if not responses:
             logger.warning('Response: %s', response_dict)
             raise MalformedResponse
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         forts = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones (negative) will be just put after
                     # time_till_hidden is below 15 min
                     # As of 2016.08.14 we don't know what values over
                     # 60 minutes are, so ignore them too
                     invalid_time = (
                         pokemon['time_till_hidden_ms'] < 0
                         or pokemon['time_till_hidden_ms'] > 900000)
                     if invalid_time:
                         continue
                     pokemons.append(
                         self.normalize_pokemon(
                             pokemon, map_cell['current_timestamp_ms']))
                 for fort in map_cell.get('forts', []):
                     if not fort.get('enabled'):
                         continue
                     if fort.get('type') == 1:  # probably pokestops
                         continue
                     forts.append(self.normalize_fort(fort))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         session.commit()
         for raw_fort in forts:
             db.add_fort_sighting(session, raw_fort)
         # Commit is not necessary here, it's done by add_fort_sighting
         logger.info(
             'Point processed, %d Pokemons and %d forts seen!',
             len(pokemons),
             len(forts),
         )
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(random.uniform(config.SCAN_DELAY,
                                   config.SCAN_DELAY + 2))
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 10
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids
         )
         if not isinstance(response_dict, dict):
             logger.warning('Response: %s', response_dict)
             raise MalformedResponse
         responses = response_dict.get('responses')
         if not responses:
             logger.warning('Response: %s', response_dict)
             raise MalformedResponse
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         forts = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones (negative) will be just put after
                     # time_till_hidden is below 15 min
                     # As of 2016.08.14 we don't know what values over
                     # 60 minutes are, so ignore them too
                     invalid_time = (
                         pokemon['time_till_hidden_ms'] < 0 or
                         pokemon['time_till_hidden_ms'] > 900000
                     )
                     if invalid_time:
                         continue
                     pokemons.append(
                         self.normalize_pokemon(
                             pokemon, map_cell['current_timestamp_ms']
                         )
                     )
                 for fort in map_cell.get('forts', []):
                     if not fort.get('enabled'):
                         continue
                     if fort.get('type') == 1:  # probably pokestops
                         continue
                     forts.append(self.normalize_fort(fort))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         session.commit()
         for raw_fort in forts:
             db.add_fort_sighting(session, raw_fort)
         # Commit is not necessary here, it's done by add_fort_sighting
         logger.info(
             'Point processed, %d Pokemons and %d forts seen!',
             len(pokemons),
             len(forts),
         )
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(
             random.uniform(config.SCAN_DELAY, config.SCAN_DELAY + 2)
         )
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 11
0
    def performMapOperations(self, i, point, session):
        self.error_code = None
        try:
            if not self.running:
                return

            if self.minorFailCount > 6:
                raise FunkyAccount

            if self.cycle == 1 and self.step == 0:
                time.sleep(1)
            else:
                secondsBetween = random.uniform(config.MIN_SCAN_DELAY,
                                                config.MIN_SCAN_DELAY + 2)
                time.sleep(secondsBetween)

                if (len(self.points) > 1):
                    point1 = self.points[i]
                    if (self.step == 0):
                        point2 = self.points[len(self.points) - 1]
                    else:
                        point2 = self.points[i - 1]

                    speed = utils.get_speed_kmh(point1, point2, secondsBetween)
                    while (speed > config.MAX_SPEED_KMH):
                        moreSleep = random.uniform(.5, 2.5)
                        time.sleep(moreSleep)
                        secondsBetween += moreSleep
                        speed = utils.get_speed_kmh(point1, point2,
                                                    secondsBetween)

            logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
            self.api.set_position(point[0], point[1], 0)
            cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
            #logger.info('Visiting point %d (%s %s) step 2', i, point[0], point[1])
            #self.api.set_position(point[0], point[1], 10)
            #logger.info('Visited point %d (%s %s) step 3', i, point[0], point[1])
            req = self.api.create_request()
            response_dict = req.get_map_objects(
                latitude=pgoapi_utils.f2i(point[0]),
                longitude=pgoapi_utils.f2i(point[1]),
                cell_id=cell_ids)
            response_dict = req.check_challenge()
            response_dict = req.get_hatched_eggs()
            response_dict = req.get_inventory()
            response_dict = req.check_awarded_badges()
            response_dict = req.download_settings()
            response_dict = req.get_buddy_walked()
            response_dict = req.call()
            self.checkResponseStatus(response_dict)
            map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
            pokemons = []
            gyms = []
            pokestops = []
            if map_objects.get('status') == 1:
                #logger.info("Status was 1")
                #logger.info("number of map objects returned: %d",len(map_objects))
                #		    logger.info(map_objects)
                for map_cell in map_objects['map_cells']:
                    #logger.info(map_cell)
                    for pokemon in map_cell.get('wild_pokemons', []):
                        #logger.info(pokemon)
                        # Care only about 15 min spawns
                        # 30 and 45 min ones (negative) will be just put after
                        # time_till_hidden is below 15 min
                        # As of 2016.08.14 we don't know what values over
                        # 60 minutes are, so ignore them too
                        invalid_time = False  #(
                        #pokemon['time_till_hidden_ms'] < 0 or
                        #                            pokemon['time_till_hidden_ms'] > 900000
                        #                       )
                        pokemon['time_logged'] = time.time()
                        #logger.info("found pokemon. time remaining: %d, %d", pokemon['time_till_hidden_ms'], pokemon['time_logged'])
                        if invalid_time:
                            logger.error("pokemon had invalid time")
                            continue

                        if config.ENCOUNTER == 1:
                            self.encounter(pokemon, point, 0)
                        else:
                            pokemon['ATK_IV'] = -2
                            pokemon['DEF_IV'] = -2
                            pokemon['STA_IV'] = -2
                            pokemon['move_1'] = -2
                            pokemon['move_2'] = -2

#logger.info("appending pokemon")
                        pokemons.append(
                            self.normalize_pokemon(
                                pokemon, map_cell['current_timestamp_ms']))
                    for fort in map_cell.get('forts', []):
                        #       logger.info(fort)
                        if not fort.get('enabled'):
                            continue
                        if fort.get('type') == 1:  # probably pokestops
                            pokestops.append(
                                self.normalize_pokestop(
                                    fort, map_cell['current_timestamp_ms']))
                        else:
                            gyms.append(self.normalize_gym(fort))
            for raw_pokemon in pokemons:
                db.add_sighting(session, raw_pokemon)
                self.seen_per_cycle += 1
                self.total_seen += 1
            session.commit()
            for raw_gym in gyms:
                db.add_gym_sighting(session, raw_gym)
            for raw_pokestop in pokestops:
                db.add_pokestop_sighting(session, raw_pokestop)
            try:
                session.commit()
            except IntegrityError:  # skip adding fort this time
                session.rollback()

            # Commit is not necessary here, it's done by add_gym_sighting
            logger.info(
                'Point processed, %d Pokemons, %d gyms, and %d pokestops seen!',
                len(pokemons), len(gyms), len(pokestops))
            # Clear error code and let know that there are Pokemon
            if self.error_code and self.seen_per_cycle:
                self.error_code = None
            self.step += 1
        except MalformedResponse:
            logger.warning('Malformed response received!')
            self.error_code = 'MALFORMED'
            #self.restart()
            #return
            self.minorFailCount = self.minorFailCount + 1
            self.performMapOperations(i, point, session)

        except CaptchaAccount:
            progressMsg = '{progress:.0f}%'.format(
                progress=(self.step / float(self.count_points) * 100))
            logger.warning(self.username + " appears to be captcha at " +
                           progressMsg)
            self.error_code = 'CAPTCHA-' + progressMsg
            username, password, service = utils.swapCaptchaWorker(
                self.worker_no, self.subNumber, self.numActiveAtOnce)
            if (username == None and password == None and service == None):
                # shoot, we are out of accounts.
                raise CaptchaAccount
            else:
                self.error_code = self.error_code + "-R"
                logger.info("Found new account, restarting")
                self.minorFailCount = self.minorFailCount + 1  # remove this if I make it resume in the middle of the path
                #self.restart(30, 90)

                for x in range(0, 6):
                    success = self.login(self.subNumber, self.numActiveAtOnce)
                    if success:
                        break
                    else:
                        logger.warning("Failed logging into " + self.username)
                        time.sleep(3)
                if not success:
                    raise FunkyAccount

                logger.info("Logged into: " + self.username)

                self.performMapOperations(i, point, session)
Esempio n. 12
0
def main():
    global add_to_db
    full_path = os.path.realpath(__file__)
    (path, filename) = os.path.split(full_path)

    args = get_args()

    if args.auth_service not in ['ptc', 'google']:
        print '[!] Invalid Auth service specified'
        return

    print('[+] Locale is ' + args.locale)
    pokemonsJSON = json.load(
        open(path + '/locales/pokemon.' + args.locale + '.json'))

    if args.debug:
        global DEBUG
        DEBUG = True
        print '[!] DEBUG mode on'

    # only get location for first run
    if not (FLOAT_LAT and FLOAT_LONG):
        print('[+] Getting initial location')
        retrying_set_location(args.location)

    if args.auto_refresh:
        global auto_refresh
        auto_refresh = int(args.auto_refresh) * 1000

    if args.ampm_clock:
        global is_ampm_clock
        is_ampm_clock = True

    api_endpoint, access_token, profile_response = login(args)

    clear_stale_pokemons()

    steplimit = int(args.step_limit)

    ignore = []
    only = []
    if args.ignore:
        ignore = [i.lower().strip() for i in args.ignore.split(',')]
    elif args.only:
        only = [i.lower().strip() for i in args.only.split(',')]

    pos = 1
    x = 0
    y = 0
    dx = 0
    dy = -1
    steplimit2 = steplimit**2
    global NEXT_LAT, NEXT_LONG
    for step in range(steplimit2):
        # Check if NEXT_LAT and NEXT_LONG have been set
        if NEXT_LAT and NEXT_LONG:
            debug('new coords have been set, breaking out of loop')
            break
        #starting at 0 index
        debug('looping: step {} of {}'.format((step + 1), steplimit**2))
        #debug('steplimit: {} x: {} y: {} pos: {} dx: {} dy {}'.format(steplimit2, x, y, pos, dx, dy))
        # Scan location math
        if -steplimit2 / 2 < x <= steplimit2 / 2 and -steplimit2 / 2 < y <= steplimit2 / 2:
            set_location_coords(x * 0.0025 + origin_lat,
                                y * 0.0025 + origin_lon, 0)
        if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
            (dx, dy) = (-dy, dx)

        (x, y) = (x + dx, y + dy)

        process_step(args, api_endpoint, access_token, profile_response,
                     pokemonsJSON, ignore, only)

        # TODO: insert to DB
        session = db.Session()
        for spawn_id in add_to_db:
            pokemon = pokemons[spawn_id]
            db.add_sighting(session, spawn_id, pokemon)
        session.commit()
        add_to_db = []

        print('Completed: ' + str(
            ((step + 1) + pos * .25 - .25) / (steplimit2) * 100) + '%')

    if (NEXT_LAT and NEXT_LONG
            and (NEXT_LAT != FLOAT_LAT or NEXT_LONG != FLOAT_LONG)):
        print('Update to next location %f, %f' % (NEXT_LAT, NEXT_LONG))
        set_location_coords(NEXT_LAT, NEXT_LONG, 0)
        NEXT_LAT = 0
        NEXT_LONG = 0
        register_background_thread(delay=1)
    else:
        set_location_coords(origin_lat, origin_lon, 0)
        register_background_thread()
Esempio n. 13
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids
         )
         if response_dict is False:
             raise CannotProcessStep
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         forts = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones will be just put after
                     # time_till_hidden is below 15 min
                     if pokemon['time_till_hidden_ms'] < 0:
                         continue
                     pokemons.append(
                         self.normalize_pokemon(
                             pokemon, map_cell['current_timestamp_ms']
                         )
                     )
                     # Prepare and send the pokemon data to the webhook listeners
                     d_t = datetime.utcfromtimestamp(
                         (pokemon['last_modified_timestamp_ms'] +
                          pokemon['time_till_hidden_ms']) / 1000.0)
                     webhook_data = {
                         'encounter_id': b64encode(str(pokemon['encounter_id'])),
                         'spawnpoint_id': pokemon['spawn_point_id'],
                         'pokemon_id': pokemon['pokemon_data']['pokemon_id'],
                         'latitude': pokemon['latitude'],
                         'longitude': pokemon['longitude'],
                         'disappear_time': calendar.timegm(d_t.timetuple()),
                         'last_modified_time': pokemon['last_modified_timestamp_ms'],
                         'time_until_hidden_ms': pokemon['time_till_hidden_ms']
                     }
                     self.send_to_webhook('pokemon', webhook_data)
                 for fort in map_cell.get('forts', []):
                     if not fort.get('enabled'):
                         continue
                     if fort.get('type') == 1:  # probably pokestops
                         continue
                     forts.append(self.normalize_fort(fort))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         session.commit()
         for raw_fort in forts:
             db.add_fort_sighting(session, raw_fort)
         # Commit is not necessary here, it's done by add_fort_sighting
         logger.info(
             'Point processed, %d Pokemons and %d forts seen!',
             len(pokemons),
             len(forts),
         )
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(
             random.uniform(config.SCAN_DELAY, config.SCAN_DELAY + 2)
         )
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Esempio n. 14
0
def main():
    global add_to_db
    full_path = os.path.realpath(__file__)
    (path, filename) = os.path.split(full_path)

    args = get_args()

    if args.auth_service not in ['ptc', 'google']:
        print '[!] Invalid Auth service specified'
        return

    print('[+] Locale is ' + args.locale)
    pokemonsJSON = json.load(
        open(path + '/locales/pokemon.' + args.locale + '.json'))

    if args.debug:
        global DEBUG
        DEBUG = True
        print '[!] DEBUG mode on'

    # only get location for first run
    if not (FLOAT_LAT and FLOAT_LONG):
      print('[+] Getting initial location')
      retrying_set_location(args.location)

    if args.auto_refresh:
        global auto_refresh
        auto_refresh = int(args.auto_refresh) * 1000

    if args.ampm_clock:
    	global is_ampm_clock
    	is_ampm_clock = True

    api_endpoint, access_token, profile_response = login(args)

    clear_stale_pokemons()

    steplimit = int(args.step_limit)

    ignore = []
    only = []
    if args.ignore:
        ignore = [i.lower().strip() for i in args.ignore.split(',')]
    elif args.only:
        only = [i.lower().strip() for i in args.only.split(',')]

    pos = 1
    x = 0
    y = 0
    dx = 0
    dy = -1
    steplimit2 = steplimit**2
    global NEXT_LAT, NEXT_LONG
    for step in range(steplimit2):
        # Check if NEXT_LAT and NEXT_LONG have been set
        if NEXT_LAT and NEXT_LONG:
            debug('new coords have been set, breaking out of loop')
            break
        #starting at 0 index
        debug('looping: step {} of {}'.format((step+1), steplimit**2))
        #debug('steplimit: {} x: {} y: {} pos: {} dx: {} dy {}'.format(steplimit2, x, y, pos, dx, dy))
        # Scan location math
        if -steplimit2 / 2 < x <= steplimit2 / 2 and -steplimit2 / 2 < y <= steplimit2 / 2:
            set_location_coords(x * 0.0025 + origin_lat, y * 0.0025 + origin_lon, 0)
        if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
            (dx, dy) = (-dy, dx)

        (x, y) = (x + dx, y + dy)

        process_step(args, api_endpoint, access_token, profile_response,
                     pokemonsJSON, ignore, only)

        # TODO: insert to DB
        session = db.Session()
        for spawn_id in add_to_db:
            pokemon = pokemons[spawn_id]
            db.add_sighting(session, spawn_id, pokemon)
        session.commit()
        add_to_db = []

        print('Completed: ' + str(
            ((step+1) + pos * .25 - .25) / (steplimit2) * 100) + '%')

    if (NEXT_LAT and NEXT_LONG and
            (NEXT_LAT != FLOAT_LAT or NEXT_LONG != FLOAT_LONG)):
        print('Update to next location %f, %f' % (NEXT_LAT, NEXT_LONG))
        set_location_coords(NEXT_LAT, NEXT_LONG, 0)
        NEXT_LAT = 0
        NEXT_LONG = 0
        register_background_thread(delay=1)
    else:
        set_location_coords(origin_lat, origin_lon, 0)
        register_background_thread()