def get_resources(region_id, date, resource_type):
    """Get resources on a date"""
    end_date_time = date.replace(hour=19, minute=0, second=0, microsecond=0)
    start_date_time = end_date_time - timedelta(1)
    session = SESSION()
    resource = {}
    resource_stats = session.query(ResourceStat) \
        .options(joinedload(ResourceStat.resource_track)) \
        .join(ResourceStat.resource_track) \
        .filter(ResourceStat.region_id == region_id) \
        .filter(ResourceTrack.resource_type == resource_type) \
        .filter(ResourceTrack.date_time >= start_date_time) \
        .filter(ResourceTrack.date_time <= end_date_time) \
        .order_by(ResourceTrack.date_time.desc()) \
        .all()
    start_limit = resource_stats[0].explored
    for resource_stat in resource_stats:
        time = resource_stat.resource_track.date_time
        resource[time] = resource_stat.explored + resource_stat.limit_left
    session.close()
    new_resource = {}
    for time, amount in resource.items():
        new_time = time.replace(tzinfo=timezone.utc).astimezone(
            tz=None) + timedelta(hours=1)
        new_resource[new_time] = amount - start_limit
    return new_resource
def get_rr_players(telegram_account):
    """Get Rival Region players associated with Telegram player"""
    LOGGER.info('"%s" get RR accounts', telegram_account.id,)
    session = SESSION()
    players = _get_rr_players(session, telegram_account.id)
    LOGGER.info('"%s" found %s RR accounts', telegram_account.id, len(players))
    session.close()
    return players
def get_latest_professor(state_id, department_type):
    """Get latest professor from database"""
    session = SESSION()
    department = get_department(session, state_id, department_type)
    professor = department.department_stats.order_by(
        DepartmentStat.date_time.desc()).first()
    session.close()
    return professor
Example #4
0
def get_active_deep_exploration(region_id):
    """Get active deep exploration in a region"""
    session = SESSION()
    deep_exploration = session.query(DeepExploration) \
        .filter(DeepExploration.region_id == region_id) \
        .filter(DeepExploration.until_date_time >= datetime.now()) \
        .first()
    session.close()
    return deep_exploration
Example #5
0
def get_current_regions(state_id):
    """Get latest professor from database"""
    session = SESSION()
    current_regions = session.query(Region) \
        .join(Region.state_regions) \
        .filter(StateRegion.state_id == state_id) \
        .filter(StateRegion.until_date_time == None) \
        .all()
    session.close()
    return current_regions
Example #6
0
def get_state(region_id):
    """Get state from region"""
    session = SESSION()
    state = session.query(State) \
        .join(State.state_regions) \
        .filter(StateRegion.region_id == region_id) \
        .filter(StateRegion.until_date_time == None) \
        .first()
    session.close()
    return state
def is_connected(telegram_id, player_id):
    """Check if account is already"""
    session = SESSION()
    player_telegram = session.query(PlayerTelegram) \
        .filter(PlayerTelegram.until_date_time == None) \
        .filter(PlayerTelegram.telegram_id == telegram_id) \
        .filter(PlayerTelegram.player_id == player_id) \
        .first()
    session.close()
    return bool(player_telegram)
Example #8
0
def get_regions(region_ids):
    """Get regions from list"""
    session = SESSION()
    regions = []
    for region_id in region_ids:
        region = session.query(Region).get(region_id)
        if not region:
            region = save_region(session, region_id)
        regions.append(region)
    session.close()
    return regions
Example #9
0
def get_regions(state_id):
    """Get region from state"""
    session = SESSION()
    state_regions = session.query(StateRegion) \
        .filter(StateRegion.state_id == state_id) \
        .filter(StateRegion.until_date_time == None) \
        .all()
    regions = []
    for state_region in state_regions:
        regions.append(state_region.region)
    session.close()
    return regions
def remove_verified_player(telegram_account_id, player_id):
    """Remove Telegram player"""
    session = SESSION()
    player_telegram = session.query(PlayerTelegram) \
        .filter(PlayerTelegram.telegram_id == telegram_account_id) \
        .filter(PlayerTelegram.player_id == player_id) \
        .filter(PlayerTelegram.until_date_time == None) \
        .first()
    if player_telegram:
        player_telegram.until_date_time = datetime.now()
        session.commit()
        return True
    return False
Example #11
0
def get_state_regions(state_id):
    """Get regions from state"""
    session = SESSION()
    state = session.query(State).get(state_id)
    region_list = []
    if state:
        region_list = state.regions.filter(
            StateRegion.until_date_time == None).all()
    else:
        save_state(session, state_id)
        LOGGER.error('State %6s: not found', state_id)
    session.close()
    return region_list
Example #12
0
def get_orders():
    """Get deep exploration orders"""
    session = SESSION()
    date_time_now = datetime.now()
    orders = session.query(DeepExplorationOrder) \
        .filter(DeepExplorationOrder.from_date_time <= date_time_now) \
        .filter(or_(
            DeepExplorationOrder.until_date_time >= date_time_now,
            DeepExplorationOrder.until_date_time == None
        )) \
        .all()
    session.close()
    return orders
def get_yesterday_professors(state_id, department_type):
    """Get professors from yesterday"""
    session = SESSION()
    department = get_department(session, state_id, department_type)
    until_date = datetime.today()
    if until_date.hour < 19:
        until_date = until_date - timedelta(1)
    until_date = until_date.replace(hour=19, minute=0, second=0)
    from_date = until_date - timedelta(1)
    professors = session.query(DepartmentStat) \
        .filter(DepartmentStat.department_id == department.id) \
        .filter(DepartmentStat.date_time >= from_date) \
        .filter(DepartmentStat.date_time < until_date) \
        .all()
    return professors
def add_telegram_account(update):
    """Add new Telegram account"""
    session = SESSION()
    telegram_account = TelegramAccount()
    telegram_account.id = update.message.from_user.id
    telegram_account.name = update.message.from_user.name
    telegram_account.registration_date = datetime.now()
    session.add(telegram_account)
    session.commit()
    session.close()
    return telegram_account
def get_amount_of_points(state_id, department_type, player_id):
    """Get amount of points in department by player id"""
    session = SESSION()
    department = get_department(session, state_id, department_type)
    until_date = datetime.today()
    if until_date.hour < 19:
        until_date = until_date - timedelta(1)
    until_date = until_date.replace(hour=19, minute=0, second=0)
    from_date = until_date - timedelta(14)
    professors = session.query(DepartmentStat) \
        .filter(DepartmentStat.department_id == department.id) \
        .filter(DepartmentStat.player_id == player_id) \
        .filter(DepartmentStat.date_time >= from_date) \
        .filter(DepartmentStat.date_time < until_date) \
        .all()
    total_points = 0
    for professor in professors:
        total_points += professor.points
    return total_points
Example #16
0
def save_deep_explorations(region_id, deep_explorations):
    """Save resources to database"""
    session = SESSION()
    for deep_exploration_id, deep_exploration_dict in deep_explorations.items(
    ):
        deep_exploration = session.query(DeepExploration).get(
            deep_exploration_id)
        if deep_exploration:
            break
        deep_exploration = DeepExploration()
        deep_exploration.id = deep_exploration_id
        region = session.query(Region).get(region_id)
        if not region:
            region = save_region(session, region_id)
        deep_exploration.region_id = region_id
        deep_exploration.resource_type = deep_exploration_dict['resource_type']
        deep_exploration.until_date_time = deep_exploration_dict[
            'until_date_time']
        session.add(deep_exploration)
    session.commit()
    session.close()
def save_professors(state_id, department_type, professors):
    """Save professors to database"""
    session = SESSION()
    department = get_department(session, state_id, department_type)

    for professor in professors:
        player = get_player(session, professor['id'], professor['name'])
        department_stat = DepartmentStat()
        department_stat.department_id = department.id
        department_stat.date_time = professor['date_time']
        department_stat.points = professor['points']
        department_stat.player_id = player.id
        session.add(department_stat)
    session.commit()
    session.close()
Example #18
0
def save_resource_market(player_market, state_market):
    """Save factories to database"""
    session = SESSION()

    market_track = get_new_market_track(session, True, True, False)
    market_track.player_resources = True
    market_track.state_resources = True
    _save_player_market(session, market_track, player_market)
    _save_state_market(session, market_track, state_market)

    session.commit()
    session.close()
Example #19
0
def get_order(order_id):
    """Get order by id"""
    session = SESSION()
    order = session.query(DeepExplorationOrder).get(order_id)
    session.close()
    return order
Example #20
0
def save_residents(region_id, residents):
    """Save residents to database"""
    session = SESSION()
    player_ids = []
    new_residents = 0
    for player_dict in residents:
        player = session.query(Player).get(player_dict['id'])
        if player is None:
            player = save_player(session, player_dict)
        player_ids.append(player.id)
        last_residency = player.residencies \
            .filter(PlayerResidency.region_id == region_id) \
            .filter(PlayerResidency.until_date_time == None) \
            .first()
        if not last_residency:
            new_residents += 1
            player_location = PlayerResidency()
            player_location.player_id = player.id
            player_location.region_id = region_id
            player_location.from_date_time = datetime.now().replace(second=0,
                                                                    minute=0)
            session.add(player_location)
    LOGGER.info('regio %6s: "%s" new residents', region_id, new_residents)
    session.commit()
    current_residents = session.query(PlayerResidency) \
        .filter(PlayerResidency.region_id == region_id) \
        .filter(PlayerResidency.until_date_time == None).all()
    for current_resident in current_residents:
        if current_resident.player_id not in player_ids:
            current_resident.until_date_time = datetime.now().replace(second=0,
                                                                      minute=0)
    session.commit()
    session.close()
Example #21
0
def save_citizens(region_id, citizens):
    """Save citizens to database"""
    session = SESSION()
    player_ids = []
    new_citizens = 0
    for player_dict in citizens:
        player = session.query(Player).get(player_dict['id'])
        if player is None:
            player = save_player(session, player_dict)
        player_ids.append(player.id)
        last_location = player.locations \
            .filter(PlayerLocation.region_id == region_id) \
            .filter(PlayerLocation.until_date_time == None) \
            .first()
        if not last_location:
            new_citizens += 1
            player_location = PlayerLocation()
            player_location.player_id = player.id
            player_location.region_id = region_id
            player_location.from_date_time = datetime.now().replace(second=0,
                                                                    minute=0)
            session.add(player_location)
    LOGGER.info('regio %6s: "%s" new citizens', region_id, new_citizens)
    session.commit()
    current_citizens = session.query(PlayerLocation) \
        .filter(PlayerLocation.region_id == region_id) \
        .filter(PlayerLocation.until_date_time == None).all()
    left_citizens = 0
    for current_citizen in current_citizens:
        if current_citizen.player_id not in player_ids:
            left_citizens += 1
            current_citizen.until_date_time = datetime.now().replace(second=0,
                                                                     minute=0)
    LOGGER.info('regio %6s: "%s" citizens left', region_id, left_citizens)
    session.commit()
    session.close()
Example #22
0
def save_regions(state_id, regions):
    """Save residents to database"""
    session = SESSION()
    region_ids = []
    state = session.query(State).get(state_id)
    if state is None:
        state = save_state(session, state_id)
    for region_dict in regions:
        region = session.query(Region).get(region_dict['id'])
        if region is None:
            region = save_region(session, region_dict)
        region_ids.append(region.id)
        state_region = session.query(StateRegion) \
            .filter(StateRegion.state_id == state.id) \
            .filter(StateRegion.region_id == region.id) \
            .filter(StateRegion.until_date_time == None) \
            .first()
        if not state_region:
            state_region = StateRegion()
            state_region.state_id = state.id
            state_region.region_id = region.id
            state_region.from_date_time = datetime.now().replace(second=0, minute=0)
            session.add(state_region)
            session.commit()

    saved_state_regions = session.query(StateRegion) \
        .filter(StateRegion.state_id == state.id) \
        .filter(StateRegion.until_date_time == None) \
        .all()
    for saved_state_region in saved_state_regions:
        if saved_state_region.region_id not in region_ids:
            saved_state_region.until_date_time = datetime.now().replace(second=0, minute=0)
    session.commit()
    session.close()
Example #23
0
def save_work_permits(state_id, work_permits):
    """Save residents to database"""
    session = SESSION()
    player_ids = []
    new_work_permits = 0
    for player_dict in work_permits:
        player = session.query(Player).get(player_dict['id'])
        if player is None:
            player = save_player(session, player_dict)
        player_ids.append(player.id)
        last_work_permit = player.state_work_permits \
            .filter(StateWorkPermit.state_id == state_id) \
            .filter(StateWorkPermit.until_date_time == None) \
            .first()
        if not last_work_permit:
            new_work_permits += 1
            state_work_permit = StateWorkPermit()
            state_work_permit.player_id = player.id
            state_work_permit.state_id = state_id
            state_work_permit.from_date_time = player_dict['from']
            session.add(state_work_permit)
    session.commit()
    LOGGER.info('state %6s: "%s" new work permits', state_id, new_work_permits)
    current_work_permits = session.query(StateWorkPermit) \
        .filter(StateWorkPermit.state_id == state_id) \
        .filter(StateWorkPermit.until_date_time == None).all()
    for current_work_permit in current_work_permits:
        if current_work_permit.player_id not in player_ids:
            current_work_permit.until_date_time = datetime.now().replace(
                second=0, minute=0)
    session.commit()
    session.close()
Example #24
0
def get_state(state_id):
    """Get regions from state"""
    session = SESSION()
    state = session.query(State).get(state_id)
    session.close()
    return state
Example #25
0
def save_factories(state_id, factories):
    """Save factories to database"""
    session = SESSION()
    session.close()

    factory_track = FactoryTrack()
    factory_track.state_id = state_id
    factory_track.date_time = datetime.now()
    session.add(factory_track)

    for factory_dict in factories:
        factory = session.query(Factory).get(factory_dict['id'])
        if factory is None:
            factory = save_factory(session, factory_dict)
        factory_stat = FactoryStat()
        factory_stat.level = factory_dict['level']
        factory_stat.experience = factory_dict['experience']
        factory_stat.wage = factory_dict['wage']
        factory_stat.workers = factory_dict['workers']
        factory_stat.factory_id = factory.id
        factory_stat.factory_track_id = factory_track.id
        session.add(factory_stat)

        current_location = session.query(FactoryLocation) \
            .filter(FactoryLocation.factory_id == factory.id) \
            .filter(FactoryLocation.until_date_time == None).first()

        if not current_location or current_location.region_id != factory_dict[
                'region_id']:
            region = session.query(Region) \
                .filter(Region.id == factory_dict['region_id']).first()
            factory_location = FactoryLocation()
            factory_location.factory_id = factory.id
            factory_location.region_id = region.id
            factory_location.from_date_time = datetime.now()
            session.add(factory_location)
            if current_location:
                current_location.until_date_time = datetime.now()

    session.commit()
    session.close()
def verify_rr_player(telegram_id, player_id):
    """Verify RR player in database"""
    session = SESSION()
    telegram_account = _get_telegram_account(session, telegram_id)
    players = _get_rr_players(session, telegram_id)
    for player in players:
        if player.id == player_id:
            LOGGER.info(
                '"%s" player already connected "%s"',
                telegram_id,
                player_id
            )
            session.close()
            return

    active_player_telegrams = session.query(PlayerTelegram) \
        .filter(PlayerTelegram.until_date_time == None) \
        .filter(PlayerTelegram.player_id == player_id) \
        .all()
    for active_player_telegram in active_player_telegrams:
        LOGGER.info(
            '"%s" unconnect player "%s"',
            active_player_telegram.telegram_id,
            player_id
        )
        active_player_telegram.until_date_time = datetime.now()

    LOGGER.info(
        '"%s" connecting player "%s"',
        telegram_id,
        player_id
    )
    player_telegram = PlayerTelegram()
    player_telegram.telegram_id = telegram_account.id
    player_telegram.player_id = player_id
    player_telegram.from_date_time = datetime.now()
    session.add(player_telegram)
    session.commit()
    session.close()
Example #27
0
def get_region(region_id):
    """Get region by id"""
    session = SESSION()
    region = session.query(Region).get(region_id)
    session.close()
    return region
def get_telegram_account(telegram_id):
    """Get Telegram account"""
    session = SESSION()
    telegram_account = _get_telegram_account(session, telegram_id)
    session.close()
    return telegram_account
Example #29
0
def save_player_market(market):
    """Save player market"""
    session = SESSION()
    market_track = get_new_market_track(session, True, False, False)
    session.add(market_track)
    _save_player_market(session, market_track, market)
def get_work_percentage(state_id, resource_type, end_date_time, hours, times):
    """Get work percentage for state in last x hours"""
    end_date_time = end_date_time.replace(minute=0, second=0, microsecond=0)
    deep = bool(resource_type)

    session = SESSION()
    data = {
        0: {
            'date':
            end_date_time,
            'stats':
            _get_state_stat(session, state_id, resource_type, end_date_time,
                            deep)
        }
    }
    for i in range(times, 0, -1):
        current_date_time = end_date_time - timedelta(hours=hours * i)
        data[i] = {
            'date':
            current_date_time,
            'stats':
            _get_state_stat(session, state_id, resource_type,
                            current_date_time, deep)
        }
    session.close()

    regions = {}
    for region_id, stat in data[0]['stats'].items():
        regions[region_id] = stat.region.name

    for i in range(0, times):
        data[i]['progress'] = {}
        reset_date_time = data[i + 1]['date']
        if reset_date_time.hour >= 19:
            reset_date_time = reset_date_time + timedelta(1)
        reset_date_time = reset_date_time.replace(hour=19)
        time_left = reset_date_time - data[i]['date']
        if time_left.seconds != 0:
            seconds_left = time_left.seconds
        else:
            seconds_left = 86400
        for region_id, stat in data[i]['stats'].items():
            if i + 1 not in data or stat.region_id not in data[i + 1]['stats']:
                continue
            next_stat = data[i + 1]['stats'][stat.region_id]
            if seconds_left == 82800:
                mined = RESOURCE_MAX[
                    resource_type] + next_stat.explored - stat.total()
                required = next_stat.total() / (seconds_left / (hours * 3600))
            else:
                mined = next_stat.total() - stat.total()
                required = next_stat.total() / (seconds_left / (hours * 3600))

            if required != 0:
                coefficient = 100 / RESOURCE_MAX[resource_type]
                percentage = (mined / required -
                              1) * next_stat.total() * coefficient + 100
            else:
                percentage = 100
            data[i]['progress'][stat.region_id] = percentage
            # print('{:4} left: {:3} mined: {:3} required: {:6.2f} percentage: {:6.2f}'.format(
            #     stat.region_id, next_stat.total(), mined, required, percentage
            # ))

    message_text = ''
    message_text += '{:17}: {:>8}\n'.format('region', 'workers')
    for date in data.values():
        if 'progress' in date:
            for region_id, progress in sorted(date['progress'].items(),
                                              key=lambda x: x[1]):
                message_text += '{:17}: {:6.2f} %\n'.format(
                    regions[region_id].replace('Netherlands', 'NL'), progress)
    return message_text