Skip to content

Commit

Permalink
Merge branch 'cc004:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
666dechaoge authored Oct 14, 2024
2 parents 2f0b0d7 + 966ed24 commit b5cc7a4
Show file tree
Hide file tree
Showing 26 changed files with 1,358 additions and 409 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
自动清日常
bug反馈/意见/交流群: 885228564

请先运行一次`_download_web.py`下载前端资源。
请先运行一次`python3 _download_web.py`下载前端资源。

如果网络不好,可自行[下载压缩包](https://github.com/Lanly109/AutoPCR_Web/releases/latest),然后`python3 _download_web.py /path/to/zip`安装。

## HTTP 服务器模式

```bash
py -3.8 httpserver_test.py
python3 _httpserver_test.py
```

访问`/daily/login`
Expand Down
75 changes: 45 additions & 30 deletions _download_web.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import asyncio
import aiohttp
from requests import get
import os
import shutil

async def get_latest_release_info(owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
response = get(url)
if response.ok:
release_info = response.json()
tag_name = release_info['tag_name']
assets = release_info['assets']
asset_download_urls = [asset['browser_download_url'] for asset in assets]
return tag_name, asset_download_urls
else:
print(response.status_code)
print(response.json())
return None, None
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.ok:
release_info = await response.json()
tag_name = release_info['tag_name']
assets = release_info['assets']
asset_download_urls = [asset['browser_download_url'] for asset in assets]
return tag_name, asset_download_urls
else:
print(response.status)
print(await response.json())
return None, None

path = os.path.dirname(os.path.abspath(__file__))

Expand All @@ -37,37 +37,42 @@ async def save_version(version):
f.write(version)

async def download_assets(asset_download_urls):
web_path = os.path.join(path, "autopcr", "http_server", "ClientApp")
if not os.path.exists(web_path):
os.makedirs(web_path)
ret = []
async with aiohttp.ClientSession() as session:
for url in asset_download_urls:
async with session.get(url) as response:
if response.status == 200:
filename = url.split('/')[-1]
print(f"Downloading {filename}")
filepath = os.path.join(path, filename)
print(f"Downloading {filename} -> {filepath}")
with open(filepath, 'wb') as f:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
print(f"Downloaded {filename}")

shutil.rmtree(web_path)
print(f"Removed old web file")

import zipfile
with zipfile.ZipFile(filepath, 'r') as zip_ref:
zip_ref.extractall(web_path)
print(f"Unzipped {filename}")

os.remove(filepath)
print(f"Delete {filename}")
ret.append(filepath)
else:
print(f"Failed to download {url}")
raise Exception(f"Failed to download {url}")
return ret

async def extract_web(filepaths):
web_path = os.path.join(path, "autopcr", "http_server", "ClientApp")
if not os.path.exists(web_path):
os.makedirs(web_path)

print(f"Removed old web file")
shutil.rmtree(web_path)

for filepath in filepaths:
print(f"Unzipped {filepath}")
import zipfile
with zipfile.ZipFile(filepath, 'r') as zip_ref:
zip_ref.extractall(web_path)

print(f"Delete {filepath}")
os.remove(filepath)

async def do_download():
owner = 'Lanly109'
Expand All @@ -76,14 +81,24 @@ async def do_download():
if latest_release_tag and asset_download_urls:
print(f"Latest release tag: {latest_release_tag}")
if await check_version(latest_release_tag):
await download_assets(asset_download_urls)
filepaths = await download_assets(asset_download_urls)
await extract_web(filepaths)
await save_version(latest_release_tag)
else:
print("Already up to date")
else:
print("Failed to fetch latest release info")
raise Exception("Failed to fetch latest release info")

async def main(zips):
if zips:
await extract_web(zips)
else:
await do_download()


if __name__ == "__main__":
import sys
zips = sys.argv[1:]
loop = asyncio.get_event_loop()
loop.run_until_complete(do_download())
loop.run_until_complete(main(zips))
35 changes: 16 additions & 19 deletions autopcr/core/datamgr.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,28 +162,18 @@ def clear_inventory(self):
self.hatsune_quest_dict.clear()

def get_unique_equip_material_demand(self, equip_slot:int, unit_id: int, token: ItemType) -> int:
if unit_id not in db.unit_unique_equip[equip_slot]:
return 0
equip_id = db.unit_unique_equip[equip_slot][unit_id].equip_id
rank = self.unit[unit_id].unique_equip_slot[0].rank if unit_id in self.unit and self.unit[unit_id].unique_equip_slot else -1
return (
flow(db.unique_equip_required[equip_id].items())
.where(lambda x: x[0] >= rank)
.select(lambda x: x[1][token])
.sum()
)
start_rank = self.unit[unit_id].unique_equip_slot[0].rank if unit_id in self.unit and self.unit[unit_id].unique_equip_slot else 0
demand = db.get_unique_equip_material_demand(unit_id, equip_slot, start_rank, db.unique_equipment_max_rank[equip_slot])
return demand.get(token, 0)

def get_unit_eqiup_demand(self, unit_id: int) -> typing.Counter[ItemType]:
unit = self.unit[unit_id]
unit_id = unit.id
rank = unit.promotion_level

return db.craft_equip(
flow(db.unit_promotion_equip_count[unit_id].items())
.where(lambda x: x[0] >= rank)
.select(lambda x: x[1])
.sum(seed=Counter()) -
Counter((eInventoryType(eInventoryType.Equip), equip.id) for equip in unit.equip_slot if equip.is_slot)
)[0]
equip_slot = [equip.is_slot for equip in unit.equip_slot]
equips = db.get_rank_promote_equip_demand(unit_id, rank, equip_slot, db.equip_max_rank, db.equip_max_rank_equip_slot)
equip_demand, mana = db.craft_equip(equips)
return equip_demand

def get_exceed_level_unit_demand(self, unit_id: int, token: ItemType) -> int:
if unit_id in self.unit and self.unit[unit_id].exceed_stage:
Expand Down Expand Up @@ -220,7 +210,7 @@ def get_library_unit_data(self) -> List:
"r": str(unit.unit_rarity),
"u": hex(unit.id // 100)[2:],
"t": f"{db.equip_max_rank}.{db.equip_max_rank_equip_num}",
"q": str(db.unique_equip_rank[unit.unique_equip_slot[0].rank].enhance_level) if unit.unique_equip_slot and unit.unique_equip_slot[0].rank > 0 else "0",
"q": str(db.unique_equip_rank[1][unit.unique_equip_slot[0].rank].enhance_level) if unit.unique_equip_slot and unit.unique_equip_slot[0].rank > 0 else "0",
"b": "true" if unit.exceed_stage else "false",
"f": False
})
Expand Down Expand Up @@ -415,6 +405,9 @@ def recover_max_time(self, quest: int) -> int:
else: # hatsune, shiori 0
return self.settings.hatsune_recover_challenge_count.recovery_max_count

def filter_inventory(self, filter: Callable) -> List[ItemType]:
return [item for item in self._inventory if filter(item) and self._inventory[item] > 0]

def get_inventory(self, item: ItemType) -> int:
return self._inventory.get(item, 0)

Expand Down Expand Up @@ -455,6 +448,10 @@ def is_mission_finished(self, system_id: int):
db.daily_mission_data[x.mission_id].system_id == system_id)
)) != 0

def get_not_enough_item(self, demand: typing.Counter[ItemType]) -> List[Tuple[ItemType, int]]:
bad = [(item, cnt - self.get_inventory(item)) for item, cnt in demand.items() if cnt > self.get_inventory(item)]
return bad

async def request(self, request: Request[TResponse], next: RequestHandler) -> TResponse:
resp = await next.request(request)
if resp: await resp.update(self, request)
Expand Down
81 changes: 77 additions & 4 deletions autopcr/core/pcrclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,40 @@ async def season_ticket_new_accept(self, season_id: int, mission_id: int):
req.mission_id = mission_id
return await self.request(req)

async def deck_update(self, deck_number: int, units: List[int], sorted: bool = False):
async def deck_update(self, deck_number: int, units: List[int]):
req = DeckUpdateRequest()
req.deck_number = deck_number
cnt = len(units)
if not sorted:
units = db.deck_sort_unit(units)
units = db.deck_sort_unit(units)
for i in range(1, 6):
setattr(req, f"unit_id_{i}",units[i - 1] if i <= cnt else 0)
return await self.request(req)

async def set_growth_item_unique(self, unit_id: int, item_id: int):
req = UnitSetGrowthItemUniqueRequest()
req.unit_id = unit_id
req.item_id = item_id
return await self.request(req)

async def set_my_party_tab(self, tab_number: int, tab_name: str):
req = SetMyPartyTabRequest()
req.tab_number = tab_number
req.tab_name = tab_name
return await self.request(req)

async def set_my_party(self, tab_number: int, party_number: int, party_label_type: int, party_name: str, units: List[int], change_rarity_unit_list: List[ChangeRarityUnit]):
req = SetMyPartyRequest()
req.tab_number = tab_number
req.party_number = party_number
req.party_label_type = party_label_type
req.party_name = party_name
cnt = len(units)
units = db.deck_sort_unit(units)
for i in range(1, 6):
setattr(req, f"unit_id_{i}", units[i - 1] if i <= cnt else 0)
req.change_rarity_unit_list = change_rarity_unit_list
return await self.request(req)

async def deck_update_list(self, deck_list: List):
req = DeckUpdateListRequest()
req.deck_list = deck_list
Expand Down Expand Up @@ -126,6 +150,55 @@ async def equipment_enhance(self, unit_id: int, equip_slot_num: int, current_enh
req.item_list = [InventoryInfoPost(id=item[1], type=eInventoryType.Item, count=count) for item, count in items.items()]
return await self.request(req)

async def unique_equip_free_enhance(self, unit_id: int, equip_slot_num: int, current_enhancement_pt: int, after_enhancement_pt: int):
req = EquipmentFreeMultiEnhanceUniqueRequest()
req.unit_id = unit_id
req.equip_slot_num = equip_slot_num
req.current_enhancement_pt = current_enhancement_pt
req.after_enhancement_pt = after_enhancement_pt
return await self.request(req)

async def equipment_rankup_unique(self, unit_id: int, equip_slot_num: int, equip_recipe_dict: typing.Counter[ItemType], item_recipe_dict: typing.Counter[ItemType], current_rank: int):
req = UniqueEquipRankupRequest()
req.unit_id = unit_id
req.equip_slot_num = equip_slot_num
req.equip_recipe_list = [UserEquipParameterIdCount(id=item[1], count=count) for item, count in equip_recipe_dict.items()]
req.item_recipe_list = [UserEquipParameterIdCount(id=item[1], count=count) for item, count in item_recipe_dict.items()]
req.current_rank = current_rank
return await self.request(req)

async def equipment_craft_unique(self, equip_id: int, equip_recipe_dict: typing.Counter[ItemType], item_recipe_dict: typing.Counter[ItemType], current_equip_num: int):
req = UniqueEquipCraftRequest()
req.equip_id = equip_id
req.equip_recipe_list = [UserEquipParameterIdCount(id=item[1], count=count) for item, count in equip_recipe_dict.items()]
req.item_recipe_list = [UserEquipParameterIdCount(id=item[1], count=count) for item, count in item_recipe_dict.items()]
req.current_equip_num = current_equip_num
await self.request(req)

async def equipment_multi_enhance_unique(self, unit_id: int, equip_slot_num: int, current_gold_num: int, craft_equip_recipe_list: List[EnhanceRecipe], craft_item_recipe_list: List[EnhanceRecipe], rank_up_equip_recipe_list: List[EnhanceRecipe], rank_up_item_recipe_list: List[EnhanceRecipe], rank_up_exp_potion_list: List[EnhanceRecipe], current_rank: int, after_rank: int, enhancement_item_list: List[EnhanceRecipe], current_enhancement_pt: int): # 仅用于equipment_craft_unique紧接着调用来装备
req = UniqueEquipMultiEnhanceRequest()
req.unit_id = unit_id
req.equip_slot_num = equip_slot_num
req.current_gold_num = current_gold_num
req.craft_equip_recipe_list = craft_equip_recipe_list
req.craft_item_recipe_list = craft_item_recipe_list
req.rank_up_equip_recipe_list = rank_up_equip_recipe_list
req.rank_up_item_recipe_list = rank_up_item_recipe_list
req.rank_up_exp_potion_list = rank_up_exp_potion_list
req.current_rank = current_rank
req.after_rank = after_rank
req.enhancement_item_list = enhancement_item_list
req.current_enhancement_pt = current_enhancement_pt
return await self.request(req)

async def equipment_enhance_unique(self, unit_id: int, equip_slot_num: int, items: typing.Counter[ItemType], current_enhancement_pt: int):
req = UniqueEquipEnhanceRequest()
req.unit_id = unit_id
req.equip_slot_num = equip_slot_num
req.item_list = [InventoryInfoPost(id=item[1], type=eInventoryType.Item, count=count) for item, count in items.items()]
req.current_enhancement_pt = current_enhancement_pt
return await self.request(req)

async def equipment_free_enhance(self, unit_id: int, equip_slot_num: int, after_equip_level: int):
req = EquipmentFreeEnhanceRequest()
req.unit_id = unit_id
Expand Down Expand Up @@ -215,7 +288,7 @@ async def prepare_mana(self, mana: int):
if self.data.get_mana() >= mana:
return True
elif self.data.get_mana(include_bank = True) >= mana:
await self.draw_from_bank(mana, mana - self.data.get_mana())
await self.draw_from_bank(self.data.user_gold_bank_info.bank_gold, mana - self.data.get_mana())
return True
else:
return False
Expand Down
12 changes: 8 additions & 4 deletions autopcr/core/sdkclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Tuple
from abc import abstractmethod
from ..sdk.validator import Validator
from ..sdk.bsgamesdk import captch
from copy import deepcopy
from ..constants import DEFAULT_HEADERS, IOS_HEADERS

Expand All @@ -12,10 +11,12 @@ class platform(Enum):

class account:
type: platform
qq: str
username: str
password: str

def __init__(self, usr: str, pwd: str, type: platform):
def __init__(self, qid: str, usr: str, pwd: str, type: platform):
self.qq = qid
self.username = usr
self.password = pwd
self.type = type
Expand All @@ -42,8 +43,7 @@ def __init__(self, info: account, captchaVerifier=Validator, errlogger=_defaultL
async def login(self) -> Tuple[str, str]: ...

async def do_captcha(self):
cap = await captch()
return await self.captchaVerifier(self.account, cap['gt'], cap['challenge'], cap['gt_user_id'])
return await self.captchaVerifier(self.qq)

def header(self):
if self._account.type == platform.Android:
Expand Down Expand Up @@ -75,6 +75,10 @@ def channel(self):
@property
def account(self):
return self._account.username

@property
def qq(self):
return self._account.qq

@property
@abstractmethod
Expand Down
2 changes: 1 addition & 1 deletion autopcr/core/sessionmgr.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ async def _ensure_token(self, next: RequestHandler):
raise
finally:
from ..sdk.validator import validate_dict, ValidateInfo
validate_dict[self._account] = ValidateInfo(status="ok")
validate_dict[self.sdk.qq].append(ValidateInfo(status="ok"))

async def _login(self, next: RequestHandler):
if os.path.exists(self.cacheFile):
Expand Down
Loading

0 comments on commit b5cc7a4

Please sign in to comment.