Ejemplo n.º 1
0
 def test_get_ship_data(self):
     with app.app_context():
         psa = PixelStarshipsApi()
         id = psa.get_user_id('adam')
         data = psa.inspect_ship(id)
         pprint(data)
     assert True
Ejemplo n.º 2
0
 def test_new_token(self):
     # Force a new token
     DEV_CONFIG['DEV_MODE'] = True
     psa = PixelStarshipsApi()
     print(psa.token)
     psa.get_new_token()
     print(psa.token)
     assert True
Ejemplo n.º 3
0
def load_players():
    push_context()
    psa = PixelStarshipsApi()
    alliances = psa.get_alliances()

    users = psa.get_top_users()
    process_users(users)

    count = 0
    for alliance_id, alliance in list(alliances.items()):
        try:
            count += 1
            print(count, '------', alliance['name'])
            users = psa.get_alliance_users(alliance_id)
            process_users(users)
        except Exception as e:
            print('*** PROBLEM LOADING ***', e)
            pass
Ejemplo n.º 4
0
def check_market():
    push_context()
    log.info('Checking market prices')

    psa = PixelStarshipsApi()
    market_data = psa.get_market_data()
    for k, v in market_data.items():
        listing = Listing(id=k,
                          sale_at=v['sale_at'],
                          item_name=v['item_name'],
                          item_id=v['item_id'],
                          amount=v['amount'],
                          currency=v['currency'],
                          price=v['price'],
                          user_id=v['user_id'],
                          modification=v['modification'])
        db.session.merge(listing)

    log.info('{} listings updated'.format(len(market_data)))
    db.session.commit()
Ejemplo n.º 5
0
 def test_ship_data(self):
     psa = PixelStarshipsApi()
     # ship, user, chars, rooms = psa.summarize_ship(self.TEST_USER_ID)
     ship, user, chars, rooms, items = Ship('adam').summarize()
     if ship:
         print(ship)
         # print(user)
         # print(len(chars), chars)
         # print(len(rooms), rooms)
         # print(len(items), items)
     assert True
Ejemplo n.º 6
0
    def cycle_token(self):
        from ps_client import PixelStarshipsApi
        # print('cycling token')
        url = (PixelStarshipsApi().server + '/UserService/DeviceLogin8'
               '?deviceKey={}'
               '&isJailBroken=false'
               '&checksum={}'
               '&deviceType=DeviceTypeMac'
               '&languagekey=en'
               '&advertisingKey=%22%22'.format(self.key, self.checksum))

        r = requests.post(url)
        root = ElementTree.fromstring(r.text)
        self.token = root.find('UserLogin').attrib['accessToken']
        self.expires_at = datetime.now() + timedelta(hours=12)
        db.session.commit()
Ejemplo n.º 7
0
def get_assets():
    if not os.path.exists(IMAGE_DIR):
        os.mkdir(IMAGE_DIR)

    psa = PixelStarshipsApi()
    sprites = psa.sprite_map

    for k, v in sprites.items():
        num = v['image_file']
        print(k, num)
        filename = IMAGE_DIR + '/{}.png'.format(num)

        if not os.path.isfile(filename):
            print('getting', filename)
            url = PS_ASSET_URL.format(num)
            try:
                request.urlretrieve(url, filename)
            except Exception as e:
                print('ERROR', e)
Ejemplo n.º 8
0
 def test_get_pss_access_token(self):
     psa = PixelStarshipsApi()
     print(psa.token)
     assert True
Ejemplo n.º 9
0
 def test_generate_device(self):
     print(PixelStarshipsApi().generate_device())
Ejemplo n.º 10
0
 def test_checksum(self):
     s = '32598c26ec94'
     checksum = 'a7666d700ff92a35459daa6227eb28e0'
     print(s, checksum, PixelStarshipsApi().md5_checksum(s))
Ejemplo n.º 11
0
    def test_device_key_gen(self):
        device_key = '32598c26ec94'
        checksum = 'a7666d700ff92a35459daa6227eb28e0'

        print(PixelStarshipsApi().create_device_key())
Ejemplo n.º 12
0
 def test_get_verification_data(self):
     push_context()
     psa = PixelStarshipsApi()
     r = psa.get_verification_data('Sokitume')
     print(r)
Ejemplo n.º 13
0
 def test_change_data(self):
     push_context()
     psa = PixelStarshipsApi()
     for r in psa.change_data:
         print(r)
Ejemplo n.º 14
0
 def test_sprite_style(self):
     psa = PixelStarshipsApi()
     print(psa.sprite_data(655))
     assert True
Ejemplo n.º 15
0
 def test_upgrade_map(self):
     psa = PixelStarshipsApi()
     print(psa.upgrade_map)
     assert True
Ejemplo n.º 16
0
 def test_get_user_id(self):
     push_context()
     psa = PixelStarshipsApi()
     id = psa.get_user_id('jy3p')
     print(id)
     assert True
Ejemplo n.º 17
0
class Ship:
    # Represents a ship

    psa = PixelStarshipsApi()

    def __init__(self, name):
        self.name = name
        self.upgrades = []

    def add_upgrade(self, description, amount, currency, construction_time):
        self.upgrades.append(
            dict(description=description, amount=amount, currency=currency, seconds=construction_time)
        )

    def summarize(self, user_id=None):
        user_id = user_id or self.psa.get_user_id(self.name)
        if not user_id:
            return None, None, None, None, None, None
        data = self.psa.inspect_ship(user_id)
        if 'InspectShip' in data:   # Only seen on admin players so far
            return None, None, None, None, None, None
        return self.summarize_ship(data)

    def summarize_ship(self, data):
        user_d = data['ShipService']['InspectShip']['User']
        ship_d = data['ShipService']['InspectShip']['Ship']
        user = dict(
            id=user_d['@Id'],
            name=user_d['@Name'],
            sprite=self.psa.sprite_data(int(user_d['@IconSpriteId'])),
            alliance_name=user_d.get('@AllianceName'),
            alliance_sprite=self.psa.sprite_data(int(user_d.get('@AllianceSpriteId'))),
            trophies=int(user_d['@Trophy']),
            last_date=user_d['@LastAlertDate'],
        )

        ship_id = int(ship_d['@ShipDesignId'])
        immunity_date = ship_d['@ImmunityDate']
        ship_level = self.psa.ship_map[ship_id]['level']

        char_list = ship_d['Characters']['Character'] if ship_d['Characters'] else []
        if type(char_list) is not list:
            char_list = [char_list]

        chars = [self.get_char(x, ship_level, i + 1) for i, x in enumerate(char_list)]

        room_sorted_chars = sorted(chars, key=itemgetter('room_id'))
        chars_by_room = {k: list(v) for k, v in groupby(room_sorted_chars, key=itemgetter('room_id'))}
        rooms = [
            dict(
                self.psa.interiorize(int(x['@RoomDesignId']), ship_id),
                design_id=int(x['@RoomDesignId']),
                id=int(x['@RoomId']),
                row=int(x['@Row']),
                column=int(x['@Column']),
                chars=list(chars_by_room.get(int(x['@RoomId']), [])),
                construction=bool(x['@ConstructionStartDate']),
                upgradable=self.psa.is_room_upgradeable(int(x['@RoomDesignId']), ship_id),
            )
            for x in ship_d['Rooms']['Room']
        ]

        for c in chars:
            if c['upgradable']:
                cost = self.psa.char_gas[c['level']] * (1 - self.psa.ship_level_to_discount[ship_level] / 100)
                self.add_upgrade(c['name'], cost, 'gas', 0)

        for r in rooms:
            if r['upgradable']:
                upgrade = self.psa.get_upgrade_room(r['design_id'])
                if upgrade:
                    cost = upgrade['upgrade_cost']
                    self.add_upgrade(
                        r['name'], cost, upgrade['upgrade_currency'], upgrade['upgrade_seconds'])

        ship = dict(
            self.psa.ship_map[ship_id],
            power_use=sum([r['power_use'] for r in rooms]),
            power_gen=sum([r['power_gen'] for r in rooms]),
            shield=sum([r['capacity'] for r in rooms if r['type'] == 'Shield']),
            char_hp=sum([c['hp'][2] for c in chars]),
            char_attack=round(sum([c['attack'][2] for c in chars]), 1),
            repair=round(sum([c['repair'][2] for c in chars]), 1),
            immunity_date=immunity_date,
        )
        layout = self.psa.get_layout(rooms, ship)
        self.psa.calc_armor_effects(rooms, layout)
        items = sorted([
            dict(
                self.psa.item_map[int(x['@ItemDesignId'])],
                quantity=int(x['@Quantity']),
            )
            for x in ship_d['Items']['Item']
            if int(x['@Quantity']) > 0
        ], key=lambda x: (self.psa.item_type[x['type']], x['name']))
        upgrades = sorted(self.upgrades, key=itemgetter('amount'))
        return ship, user, chars, rooms, items, upgrades

    def get_char(self, x, ship_level, order):
        stats = self.psa.char_map[int(x['@CharacterDesignId'])].copy()
        items = self.get_char_items(x)
        level = int(x['@Level'])
        stamina = int(x['@StaminaImprovement'])
        progression_type = stats['progression_type']

        training = stamina
        for k, training_key in self.psa.stat_map.items():
            (start, end) = stats[k]
            improvement = int(x[training_key]) if training_key in x else 0
            training += improvement

            current = start
            if progression_type == 'Linear':
                current += (end - start) * ((level - 1) / 39)
            elif progression_type == 'EaseIn':
                current += (end - start) * ((level - 1) / 39) ** 2
            elif progression_type == 'EaseOut':
                current += (end - start) * ((level - 1) / 39) ** .5

            stats[k] = [start, end, current, improvement, 0]    # start, end, current, +% +

        stats['stamina'] = stamina

        # Item effects
        for part, i in items.items():
            e = i['enhancement']
            if e in self.psa.enhance_stats:
                stats[self.psa.enhance_stats[e]] += i['bonus']
            # elif e == 'science':    # Science was removed from chars, as was shield... 4/26/2018
            #     pass
            else:
                stats[e][4] += i.get('bonus', 0)

            extra = i['extra_enhancement']
            if extra in self.psa.enhance_stats:
                stats[self.psa.enhance_stats[extra]] += i['extra_bonus']
            elif extra:
                stats[extra][4] += i['extra_bonus']

        # Final calculations and rounding
        for s in self.psa.stat_map:
            train_scale = (1 + stats[s][3] / 100)

            if s == 'ability':
                item_scale = (1 + stats[s][4] / 100)
                item_add = 0
            else:
                item_scale = 1
                item_add = stats[s][4]

            stats[s][2] = stats[s][2] * train_scale * item_scale + item_add
            stats[s][1] = stats[s][1] * train_scale * item_scale + item_add

            for i in range(0, 5):
                if s == 'hp' and i == 2:
                    stats[s][i] = int(round(stats[s][i]))
                else:
                    stats[s][i] = round(stats[s][i], 1)

        stats['training'] = training
        stats['level'] = level
        stats['char_name'] = x['@CharacterName']
        stats['room_id'] = int(x['@RoomId'])
        stats['character_id'] = int(x['@CharacterId'])
        stats['xp'] = int(x['@Xp'])
        stats['order'] = order
        target_xp = self.psa.leg_level_xp[stats['level']] if ('legendary' == stats['rarity']) \
            else self.psa.level_xp[stats['level']]
        stats['upgradable'] = stats['xp'] >= target_xp and stats['level'] < min(ship_level * 4, 40)
        stats['equipment'] = dict(stats['equipment'], **items)
        stats['char_id'] = int(x['@CharacterId'])
        return stats

    def get_char_items(self, char_data):
        item_data = char_data['Items']
        if item_data:
            items = item_data['Item']
            if type(items) is not list:
                items = [items]

            item_list = [
                dict(
                    self.psa.item_map[int(i['@ItemDesignId'])],
                    extra_enhancement=i.get('@BonusEnhancementType', '').lower(),
                    extra_bonus=float(i.get('@BonusEnhancementValue', 0))
                )
                for i in items
            ]
            items = {i['slot']: i for i in item_list}
            return items
        return {}
Ejemplo n.º 18
0
 def test_load_room_map(self):
     push_context()
     psa = PixelStarshipsApi()
     psa._load_room_map()
     assert True
Ejemplo n.º 19
0
 def test_test_prices(self):
     push_context()
     psa = PixelStarshipsApi()
     data = psa._load_prices()
     print(data)
     assert True
Ejemplo n.º 20
0
 def test_market_data(self):
     psa = PixelStarshipsApi()
     data = psa.get_market_data()
     print(data)
     assert True
Ejemplo n.º 21
0
 def test_get_ship_data(self):
     psa = PixelStarshipsApi()
     id = psa.get_user_id('jy3p')
     data = psa.inspect_ship(id)
     pprint(data)
     assert True
Ejemplo n.º 22
0
 def test_prestige(self):
     push_context()
     psa = PixelStarshipsApi()
     r = psa.prestige_data(195)
     print(r)
Ejemplo n.º 23
0
 def test_item_prices(self):
     push_context()
     psa = PixelStarshipsApi()
     r = psa.get_item_prices(103)
     print(r)
     assert True
Ejemplo n.º 24
0
def update_data():
    push_context()
    psa = PixelStarshipsApi()
    psa.update_item_data()
    psa.update_char_data()
    psa.update_room_data()
    psa.update_ship_data()
    psa.update_collection_data()
    psa.update_data(psa.uri_research, 'ResearchDesignId', 'research')
Ejemplo n.º 25
0
 def test_room_map(self):
     psa = PixelStarshipsApi()
     print(psa.room_map)
     assert True
Ejemplo n.º 26
0
 def test_add_records(self):
     push_context()
     psa = PixelStarshipsApi()
     psa.update_item_data()
     assert True
Ejemplo n.º 27
0
 def test_char_map(self):
     psa = PixelStarshipsApi()
     print(psa.char_map)
     assert True
Ejemplo n.º 28
0
 def test_read_records(self):
     push_context()
     psa = PixelStarshipsApi()
     psa._load_item_map()
     assert True
Ejemplo n.º 29
0
APP_NAME = 'pixyship'
app = Flask(APP_NAME, static_folder="./dist/static", template_folder="./dist")
app.secret_key = 'Su8#kKpY4wxMFB*P2X9a66k7%DRbHw'

# SQLAlchemy Object
app.config['SQLALCHEMY_DATABASE_URI'] = CONFIG['DSN']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

cors = CORS(
    app,
    supports_credentials=True,
)

psa = PixelStarshipsApi()


def push_context():
    """ Set the app context for repl environments like ipython. Do not use in the
    app
    """
    app.app_context().push()


@app.before_request
def before_request():
    session.permanent = False
    if os.path.exists("maintenance"):   # Check if a "maintenance" file exists (whatever it is empty or not)
        flask.abort(503)    # No need to worry about the current URL, redirection, etc
Ejemplo n.º 30
0
 def test_setting_service(self):
     psa = PixelStarshipsApi()
     print(psa.get_settings())